本文介绍了在Javascript中获取查询字符串数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个使用get方法并包含数组的表单:
I have a form that uses the get method and contains an array:
http://www.example.com?name [ ] = hello& name [] = world
我正在尝试使用JavaScript或jQuery检索数组值'hello'和'world' 。
I'm trying to retrieve array values 'hello' and 'world' using JavaScript or jQuery.
我已经看过Stack Overflow上的类似解决方案(例如)但它们似乎只处理参数而不是数组。
I've had a look at similar solutions on Stack Overflow (e.g. How can I get query string values in JavaScript?) but they seem to only deal with parameters rather than arrays.
是否可以获取数组值?
推荐答案
你去:
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));
这篇关于在Javascript中获取查询字符串数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!