天天看點

js文字進行編碼相關函數诠釋

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(" target="_blank" rel="external nofollow" 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】