程式設計-解析Location.search查詢字串
阿新 • • 發佈:2019-01-27
Location.search返回的字串以‘ ?’開頭,各引數間以‘&’相連,如url?a=1&b=2
//解析查詢字串
function getQueryStringArgs() {
//取得查詢字串,並去掉開頭'?'
var qs = location.search.length?location.search.substring(1):'';
//儲存資料的物件
var args={},
//以分割符'&'分割字串,並以陣列形式返回
items = qs.length?qs.split('&' ):[],
item=null,
name=null,
value=null,
i=0,
len = items.length;
//逐個將每一項新增到args物件中
for(;i<len;i++) {
item = items[i].split('=');
//解碼操作,因為查詢字串經過編碼的
name = decodeURIComponent(item[0]);
value = decodeURIComponent (item[1]);
value = item[1];
if(name.length) {
args[name] = value;
}
}
return args;
}