encodeURIComponent的使用
在說明encodeURIComponent前先介紹下 escape,encodeURI,encodeURIComponent 這三個,主要是從其他地方轉(zhuǎn)過來的(http://blog.csdn.net/fengzi_shen/archive/2009/04/01/4041488.aspx)。
js對文字進行編碼涉及3個函數(shù):escape,encodeURI,encodeURIComponent,相應(yīng)3個解碼函數(shù):unescape,decodeURI,decodeURIComponent
1、 傳遞參數(shù)時需要使用encodeURIComponent,這樣組合的url才不會被#等特殊字符截斷。
例如:<script language="javascript">document.write('<a );</script>
2、 進行url跳轉(zhuǎn)時可以整體使用encodeURI
例如:Location.href=encodeURI("http://cang.baidu.com/do/s?word=百度&ct=21");
3、 js使用數(shù)據(jù)時可以使用escape
[Huoho.Com編輯]
例如:搜藏中history紀錄。
4、 escape對0-255以外的unicode值進行編碼時輸出%u****格式,其它情況下escape,encodeURI,encodeURIComponent編碼結(jié)果相同。
最多使用的應(yīng)為encodeURIComponent,它是將中文、韓文等特殊字符轉(zhuǎn)換成utf-8格式的url編碼,所以如果給后臺傳遞參數(shù)需要使用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
現(xiàn)在說下我在傳遞非英文字符串的處理:
URL: addressgrp.action?oper=addgrp&groupname="+encodeURIComponent(groupsname)
在action獲取 groupname( getGroupname() )時并沒有進過編碼轉(zhuǎn)化,獲取的信息并不正確,經(jīng)過嘗試發(fā)現(xiàn)需要進行一次編碼轉(zhuǎn)換:String grpname= new String(getGroupname().getBytes("ISO-8859-1"), "UTF-8");
在網(wǎng)上搜索相關(guān)的信息,網(wǎng)上提供了另一種方法:在頁面上進行兩次編碼操作,然后在后臺再進行一次解碼,這是由于java后臺在獲取數(shù)據(jù)時已經(jīng)進行了一次解碼,可問題是進行一次解碼后的數(shù)據(jù)并不正確,而如果在頁面中編碼兩次然后在后臺進行一次解碼就可以獲取真確的數(shù)據(jù)。頁面URL: addressgrp.action?oper=addgrp&groupname="+ encodeURIComponent( encodeURIComponent(groupsname))
后臺獲取數(shù)據(jù): String grpname =java.net.URLDecoder.decode( getGroupname() ,"UTF-8")