取得 URL 查詢參數是常見需求。第一種方式是使用正則表達式比對參數名稱;第二種方式是將查詢字串拆成陣列後逐一組合成物件。
正則寫法適合只取單一參數,拆字串寫法則適合一次取得多個參數。
function getQueryString(name) {
var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
var r = window.location.search.substr(1).match(reg);
return r != null ? decodeURIComponent(r[2]) : null;
}function GetRequest() {
var url = location.search;
var theRequest = {};
if (url.indexOf('?') != -1) {
var str = url.substr(1).split('&');
for (var i = 0; i < str.length; i++) {
theRequest[str[i].split('=')[0]] = decodeURIComponent(str[i].split('=')[1]);
}
}
return theRequest;
}