我有一个使用 get 方法并包含一个数组的表单:
http://www.example.com?name[]=hello&name[]=world
我正在尝试使用 JavaScript 或 jQuery 检索数组值“hello”和“world”。
我在 Stack Overflow 上看过类似的解决方案(例如如何在 JavaScript 中获取查询字符串值? https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values)但它们似乎只处理参数而不是数组。
是否可以获取数组值?
就这样:http://jsfiddle.net/mm6Bt/1/ http://jsfiddle.net/mm6Bt/1/
function getURLParam(key,target){
var values = [];
if (!target) target = location.href;
key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var pattern = key + '=([^&#]+)';
var o_reg = new RegExp(pattern,'ig');
while (true){
var matches = o_reg.exec(target);
if (matches && matches[1]){
values.push(matches[1]);
} else {
break;
}
}
if (!values.length){
return null;
} else {
return values.length == 1 ? values[0] : values;
}
}
var str = 'http://www.example.com?name[]=hello&name[]=world&var1=stam';
console.log(getURLParam('name[]',str));
console.log(getURLParam('var1',str));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)