javascript中可用的編碼解碼函數(shù),有如下的組合:
-
escape(string);
unescape(string); -
encodeURI(string);
decodeURI(string); -
encodeURIComponent(string);
decodeURIComponent(string);
他們之間的區(qū)別為:
escape/unescape:
以16進(jìn)制編碼字符串,對(duì)空格、符號(hào)等字符用%xx編碼表示,對(duì)中文等字符用%uxxxx編碼表示。自javascript1.5之后,此方法已經(jīng)不被推薦使用。
encodeURI/decodeURI:
以UTF-8編碼編碼字符串,對(duì)這些字符:“
; , / ? : @ & = + $
”不做編碼。
encodeURIComponent/decodeURIComponent:
以UTF-8編碼編碼所有字符串。
因?yàn)閑scape/unescape已經(jīng)deprecated。就不說(shuō)它了,encodeURI和encodeURIComponent之前的區(qū)別用實(shí)例說(shuō)明:
比如說(shuō)要使用get方式將一個(gè)參數(shù)u,傳遞給服務(wù)器:
var
?u="index.php?blogId=1&op=Default";
var ?getURL="http://www.simplelife.cn/test.php?p="+encodeURI(u);
var ?getURL="http://www.simplelife.cn/test.php?p="+encodeURI(u);
這里,如果使用了encodeURI,那么最終的getURL的值為:
http://www.simplelife.cn/test.php?p=index.php?blogId=1&op=Default
這樣,對(duì)參數(shù)u中的字符"&op=Default",將不會(huì)作為字符串參數(shù)傳遞到服務(wù)器端,而是當(dāng)作test.php的參數(shù)傳遞過(guò)去了,因?yàn)閷?duì)"&op=Default"中的字符"&"沒(méi)有做編碼。
所以,在這種應(yīng)用場(chǎng)景下,就需要使用encodeURIComponent,編碼后的getURL值為:
http://www.simplelife.cn/test.php?p=index.php%3FblogId%3D1%26op%3DDefault
這樣,參數(shù)就可以順利傳遞過(guò)去了。在服務(wù)器端得到的字符串將是正確的u。
反之,如果需要通過(guò)get方式訪問(wèn)某一URL,但是URL中包含中文等字符,為了防止亂碼等編碼問(wèn)題,需要將URL通過(guò)encodeURI進(jìn)行編碼。