方法
封裝
function GetQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null) return decodeURIComponent(r[2]);
return null;
}
調用
alert(GetQueryString('UserName'));
說明
建議使用encodeURIComponent、encodeURI,不建議使用escape
關於三中編碼函數的區別,原博文 https://blog.csdn.net/letterTiger/article/details/79623991
關於escape,不建議使用的原因,原博文 https://blog.csdn.net/unopenmycode/article/details/78835545
摘抄:
其對編碼函數進行了修改,且對原因也進行了說明。
escape()不對“+”編碼。但是我們知道,網頁在提交表單的時候,如果有空格,則會被轉化為+字符。
服務器處理數據的時候,會把+號處理成空格。所以,使用的時候要小心。
encodeURIComponent()
最后一個Javascript編碼函數是encodeURIComponent()。
與encodeURI()的區別是,它用於對URL的組成部分進行個別編碼,而不用於對整個URL進行編碼。
因此,“; / ? : @ & = + $ , #”,這些在encodeURI()中不被編碼的符號,在encodeURIComponent()中統統會被編碼。
至於具體的編碼方法,兩者是一樣。
encodeURIComponent()相比encodeURI()要更加徹底。
為什么優先使用encodeURIComponent而不是escape?
escape方法並不編碼字符+。而我們知道,在用戶提交的表單字段中,如果有空格,則會被轉化為+字符,而服務器解析的時候則會認為+號代表空格。
由於這個缺陷,escape方法並不能正確地處理所有的非ASCII字符,你應當盡量避免使用escape方法,
取而代之,你最好選擇 encodeURIComponent()方法。
