標籤:blog http 使用 ar java 資料 div 問題 c
url傳遞參數這是很常見資料傳遞方式,但如果不注意也是很容易出現問題的。
最常見的就是url傳遞中文亂碼了以及空格被轉碼,而要避免這種問題出現的最佳解決方案是傳遞前編碼,接收資料後解碼。編碼我們用encodeURI和encodeURIComponent,解碼我們用decodeURI和decodeURIComponent。
encodeURI() 把字串編碼為 URI。(對應decodeURI)
encodeURIComponent() 把字串編碼為 URI 組件。
decodeURI() 解碼某個編碼的 URI。對應encodeURI)
decodeURIComponent() 解碼一個編碼的 URI 組件。(對應encodeURIComponent)
這兩種轉碼和解碼方式具體有什麼區別呢?看下面幾行代碼運行結果就知道了:
var urlStr="http://www.coolfish.cn/tag/url中文亂碼"; var enURI=encodeURI(urlStr); var deURI=decodeURI(urlStr); var enURIC=encodeURIComponent(urlStr); var deURIC=decodeURIComponent(urlStr);console.log("初始URL:"+urlStr);console.log("encodeURI轉碼:"+enURI);console.log("decodeURI解碼:"+deURI);console.log("encodeURIComponent轉碼:"+enURIC);console.log("decodeURIComponent解碼:"+deURIC);
運行結果:
初始URL:http://www.coolfish.cn/tag/url中文亂碼
encodeURI轉碼:http://www.coolfish.cn/tag/url%E4%B8%AD%E6%96%87%E4%B9%B1%E7%A0%81
decodeURI解碼:http://www.coolfish.cn/tag/url中文亂碼
encodeURIComponent轉碼:http%3A%2F%2Fwww.coolfish.cn%2Ftag%2Furl%E4%B8%AD%E6%96%87%E4%B9%B1%E7%A0%81
decodeURIComponent解碼:http://www.coolfish.cn/tag/url中文亂碼
可以看到encodeURIComponent轉碼的時候會把uri進行編碼(url中的://轉碼了)。
當我們的url傳遞類似callbackURL的參數的時候,最好是使用encodeURIComponent和decodeURIComponent來編碼和轉碼。
decodeURI和 decodeURIComponent以及encodeURI和encodeURIComponent的區別