Javascript下的urlencode編碼解碼方法附decodeURIComponent
2024-05-06 14:10:22
供稿:網(wǎng)友
關(guān)于在ASP(Server.UrlEncode)、PHP(urlencode())函數(shù)編碼結(jié)果,或是經(jīng)過(guò)asp、php等動(dòng)態(tài)語(yǔ)言直接寫(xiě)入COOKIES的中文字符,用JS讀取的時(shí)候,都會(huì)碰到一個(gè)編碼的問(wèn)題,那就是最終字符串被urlencode編碼了,而又時(shí)有需要從JS在客戶(hù)端去讀取這些數(shù)據(jù)。
而本文,就大概說(shuō)說(shuō)如何在js中通過(guò)系統(tǒng)自帶的函數(shù)去解決這個(gè)問(wèn)題。
而相信碰到過(guò)此問(wèn)題的朋友應(yīng)該都有所了解,目前網(wǎng)絡(luò)上流行一些js下的自定義函數(shù)去解決這個(gè)問(wèn)題,如說(shuō)vbscript(URLDecode())、javascript(UrlDecode())等。而這兩個(gè)函數(shù),都無(wú)法很好的與asp(Server.UrlEncode)、php(urlencode())這兩個(gè)函數(shù)相互通訊。
關(guān)于vbscript(function URLDecode())、javascript(function UrlDecode())在本文最后也會(huì)轉(zhuǎn)載出來(lái)。
而本文的主角就是javascript(UrlDecodedecodeURIComponent()),這個(gè)函數(shù)名稱(chēng)實(shí)在太常了,個(gè)人真的不太了解,畢竟js的系統(tǒng)函數(shù)很多,很容易遺漏。煩惱在偶然間發(fā)現(xiàn)了這個(gè)函數(shù)!
編碼函數(shù):encodeURIComponent()
解碼函數(shù):decodeURIComponent()
decodeURIComponent()語(yǔ)法
代碼如下:
decodeURIComponent(URIstring)
參 數(shù):(URIstring)必需。一個(gè)字符串,含有編碼 URI 組件或其他要解碼的文本。
返回值:URIstring 的副本,其中的十六進(jìn)制轉(zhuǎn)義序列將被它們表示的字符替換。
實(shí)例:
代碼如下:
<script type="text/javascript">
var test1="煩惱";
var test2="%E7%83%A6%E6%81%BC";
document.write("編碼(原="+test1+"):"+encodeURIComponent(test1)+ "<br />");
document.write("解碼(原="+test2+"):"+decodeURIComponent(test2));
</script>
結(jié)果:
代碼如下:
編碼(原=煩惱):%E7%83%A6%E6%81%BC
解碼(原=%E7%83%A6%E6%81%BC):煩惱
注意:本文只在UTF-8編碼環(huán)境下測(cè)試。因?yàn)樵诓煌幋a環(huán)境下,asp(Server.UrlEncode)所編譯后的代碼好像不同,有待測(cè)試!
附轉(zhuǎn)載:
vbscript(function URLDecode())
代碼如下:
<script type="text/VBscript">
<!--
Function URLDecode(enStr)
dim deStr,strSpecial
dim c,i,v
deStr=""
strSpecial="!""#$%&'()*+,.-_/:;<=>?@[/]^`{|}~%"
for i=1 to len(enStr)
c=Mid(enStr,i,1)
if c="%" then
v=eval("&h"+Mid(enStr,i+1,2))
if inStr(strSpecial,chr(v))>0 then
deStr=deStr&chr(v)
i=i+2