我有一个这样的网址:
http://www.somewhere.com/index.html?field[]=history&field[]=science&field[]=math
使用jQuery,我如何获取GET数组?
感谢。
答案 0 :(得分:6)
var str = "http://www.somewhere.com/index.html?field[]=history&field[]=science&field[]=math";
var match = str.match(/[^=&?]+\s*=\s*[^&#]*/g);
var obj = {};
for ( var i = match.length; i--; ) {
var spl = match[i].split("=");
var name = spl[0].replace("[]", "");
var value = spl[1];
obj[name] = obj[name] || [];
obj[name].push(value);
}
alert(obj["field"].join(", "))
答案 1 :(得分:1)
/*
* Returns a map of querystring parameters
*
* Keys of type <fieldName>[] will automatically be added to an array
*
* @param String url
* @return Object parameters
*/
function getParams(url) {
var regex = /([^=&?]+)=([^&#]*)/g, params = {}, parts, key, value;
while((parts = regex.exec(url)) != null) {
key = parts[1], value = parts[2];
var isArray = /\[\]$/.test(key);
if(isArray) {
params[key] = params[key] || [];
params[key].push(value);
}
else {
params[key] = value;
}
}
return params;
}