js文字进行编码相关函数诠释

来源:互联网 发布:21天学通linux c编程 编辑:程序博客网 时间:2024/05/16 07:44

ajax提交表单:为了出现中文时不出现乱码需要经过escape进行转码

通过用escape函数将中文转成如:“%u4E2D%u534E%u4EBA%u6C11%u5171%u548C%u56FD”的编码


当要显示到页面时就要通过unescape函数进行解码 方可显示正常。


js对文字进行编码涉及3个函数:escape,encodeURI,encodeURIComponent,


相应3个解码函数:unescape,decodeURI,decodeURIComponent


1)、 传递参数时需要使用encodeURIComponent,这样组合的url才不会被#等特殊字符截断。  


例如:<script language="javascript">document.write('<a href="http://passport.baidu.com/?logout&aid=7& u='+encodeURIComponent("http://cang.baidu.com/bruce42")+'">退出</a&amp; gt;');</script>


2)、 进行url跳转时可以整体使用encodeURI


例如:Location.href=encodeURI("http://cang.baidu.com/do/s?word=百度& ct=21");


3)、 js使用数据时可以使用escape


[Huoho.Com编辑]


例如:搜藏中history纪录。


4)、 escape对0-255以外的unicode值进行编码时输出%u****格式,其它情况下 escape,encodeURI,encodeURIComponent编码结果相同。


最多使用的应为encodeURIComponent,它是将中文、韩文等特殊字符转换成utf-8格式的url编码,所以如果给后台传递参数需要使用encodeURIComponent时需要后台解码对utf-8支持(form中的编码方式和当前页面编码方式相同)


escape不编码字符有69个:*,+,-,.,/,@,_,0-9,a-z,A-Z


encodeURI不编码字符有82个:!,#,$,&,',(,),*,+,,,-,.,/,:,;,=,?,@,_,~,0-9,a- z,A-Z


encodeURIComponent不编码字符有71个:!, ',(,),*,-,.,_,~,0-9,a-z,A-Z

javaScript中URL编码转换,escape() encodeURI() encodeURIComponent

另外,encodeURI/encodeURIComponent是在javascript1.5之后引进的,escape则在 javascript1.0版本就有。


escape()不编码的字符:@*/+


相对于使用escape方法,使用encodeURI方法会显得更专业一些。当你需要编码一整个URI的时候,你可以使用此方法,因为URI中的合法字符都不会被编码转换。需要注意到是字符’也是URI中的合法字符,所以也不会被编码转换。

encodeURI() 不编码的字符: ~!@#$&*()=:/,;?+''

encodeURIComponent方法在编码单个URIComponent(指请求参数)应当是最常用的。需要注意到是字符’也是URI中的合法字符,所以也不会被编码转换。

encodeURIComponent()不编码的字符: ~!*()''

JAVA后台相应处理:


如果是用escape编码 则:


通过自定义方法:

    public static String unescape(String src) {
        StringBuffer tmp = new StringBuffer();
        tmp.ensureCapacity(src.length());
        int lastPos = 0, pos = 0;
        char ch;
        while (lastPos < src.length()) {
            pos = src.indexOf("%", lastPos);
            if (pos == lastPos) {
                if (src.charAt(pos + 1) == 'u') {
                    ch = (char) Integer.parseInt(src.substring(pos + 2, pos + 6), 16);
                    tmp.append(ch);
                    lastPos = pos + 6;
                } else {
                    ch = (char) Integer.parseInt(src.substring(pos + 1, pos + 3), 16);
                    tmp.append(ch);
                    lastPos = pos + 3;
                }
            } else {
                if (pos == -1) {
                    tmp.append(src.substring(lastPos));
                    lastPos = src.length();
                } else {
                    tmp.append(src.substring(lastPos, pos));
                    lastPos = pos;
                }
            }
        }
        return tmp.toString();
    }



如果是用encodeURI编码 则:

通过java.net.Decode.decode(request.getParameter("value"),"UTF-8")进行解码 

 

参考 【http://huibin.iteye.com/blog/643869】【http://topic.csdn.net/u/20110419/10/592eb005-e65d-413a-badf-c4d45cb5f7ac.html?seed=1538315658&r=72848162#r_72848162】

原创粉丝点击