1. 程式人生 > >前端 url 引數提交有特殊字元 的解決方法

前端 url 引數提交有特殊字元 的解決方法

用 

JavaScript encodeURIComponent() 函式

定義和用法

encodeURIComponent() 函式可把字串作為 URI 元件進行編碼。

語法

encodeURIComponent(URIstring)
引數 描述
URIstring 必需。一個字串,含有 URI 元件或其他要編碼的文字。

返回值

URIstring 的副本,其中的某些字元將被十六進位制的轉義序列進行替換。

說明

該方法不會對 ASCII 字母和數字進行編碼,也不會對這些 ASCII 標點符號進行編碼: - _ . ! ~ * ' ( ) 。

其他字元(比如 :;/?:@&=+$,# 這些用於分隔 URI 元件的標點符號),都是由一個或多個十六進位制的轉義序列替換的。

提示和註釋

提示:請注意 encodeURIComponent() 函式 與 encodeURI() 函式的區別之處,前者假定它的引數是 URI 的一部分(比如協議、主機名、路徑或查詢字串)。因此 encodeURIComponent() 函式將轉義用於分隔 URI 各個部分的標點符號。

例項

在本例中,我們將使用 encodeURIComponent() 對 URI 進行編碼:

<script type="text/javascript">

document.write(encodeURIComponent("http://www.w3school.com.cn"))
document.write("<br />")
document.write(encodeURIComponent("http://www.w3school.com.cn/p 1/"))
document.write("<br />")
document.write(encodeURIComponent(",/?:@&=+$#"))

</script>

輸出:

http%3A%2F%2Fwww.w3school.com.cn
http%3A%2F%2Fwww.w3school.com.cn%2Fp%201%2F
%2C%2F%3F%3A%40%26%3D%2B%24%23