Javascript下的urlencode編碼解碼方法附decodeURIComponent
2024-05-06 14:10:22
供稿:網友
關于在ASP(Server.UrlEncode)、PHP(urlencode())函數編碼結果,或是經過asp、php等動態語言直接寫入COOKIES的中文字符,用JS讀取的時候,都會碰到一個編碼的問題,那就是最終字符串被urlencode編碼了,而又時有需要從JS在客戶端去讀取這些數據。
而本文,就大概說說如何在js中通過系統自帶的函數去解決這個問題。
而相信碰到過此問題的朋友應該都有所了解,目前網絡上流行一些js下的自定義函數去解決這個問題,如說vbscript(URLDecode())、javascript(UrlDecode())等。而這兩個函數,都無法很好的與asp(Server.UrlEncode)、php(urlencode())這兩個函數相互通訊。
關于vbscript(function URLDecode())、javascript(function UrlDecode())在本文最后也會轉載出來。
而本文的主角就是javascript(UrlDecodedecodeURIComponent()),這個函數名稱實在太常了,個人真的不太了解,畢竟js的系統函數很多,很容易遺漏。煩惱在偶然間發現了這個函數!
編碼函數:encodeURIComponent()
解碼函數:decodeURIComponent()
decodeURIComponent()語法
代碼如下:
decodeURIComponent(URIstring)
參 數:(URIstring)必需。一個字符串,含有編碼 URI 組件或其他要解碼的文本。
返回值:URIstring 的副本,其中的十六進制轉義序列將被它們表示的字符替換。
實例:
代碼如下:
<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>
結果:
代碼如下:
編碼(原=煩惱):%E7%83%A6%E6%81%BC
解碼(原=%E7%83%A6%E6%81%BC):煩惱
注意:本文只在UTF-8編碼環境下測試。因為在不同編碼環境下,asp(Server.UrlEncode)所編譯后的代碼好像不同,有待測試!
附轉載:
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