Jquery从url读取几个数组参数

时间:2013-10-15 09:25:53

标签: javascript jquery arrays urldecode

我有以下网址:

http://mydomain/Forwards?searchValue[]=Nike+Webstore&searchValue[]=Bodyman&category_filter[]=Animals+%26+Pet+Supplies&category_filter[]=Fashion&country_filter[]=Aland+Islands&country_filter[]=American+Samoa

此网址包含许多以数组形式发送的参数:

现在我希望得到每个单独的数组及其值

在上面的例子中,结果应该是这样的:

searchValue = array(
[0] = 'Nike Webstore'
[1] = 'Bodyman'
);

category_filter = array(
[0] = 'Animals & Pet Supplies'
[1] = 'Fashion'
);

country_filter = array(
[0] = 'Aland Islands'
[1] = 'American Samoa'
);

是否可以像这样得到它,如果是这样的话怎么样?我试过以下内容:

 decodeURIComponent(
    (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]

然而,在我的例子中,这只返回了1个值(Nike Webstore)。

2 个答案:

答案 0 :(得分:2)

因为参数是一个数组。以下代码将正常工作..

// our test url
var url ="http://mydomain/Forwards?searchValue[]=Nike+Webstore&searchValue[]=Bodyman&category_filter[]=Animals+%26+Pet+Supplies&category_filter[]=Fashion&country_filter[]=Aland+Islands&country_filter[]=American+Samoa" ;
// filtering the string..
var paramsList = url.slice(url.indexOf("?")+1,url.length) ;
var filteredList =  paramsList.split("&") ;

// an object to store arrays
var objArr = {} ;

// the below loop is obvious... we just remove the [] and +.. and split into pair of key and value.. and store as an array...
for (var i=0, l=filteredList.length; i <l; i +=1 ) {
  var param = decodeURIComponent(filteredList[i].replace("[]","")).replace(/\+/g," ") ;
  var pair = param.split("=") ;
  if(!objArr[pair[0]]) {  objArr[pair[0]] = [] ;}
  objArr[pair[0]].push(pair[1]);
}

console.log(objArr);

会给我们......

[object Object] {
  category_filter: ["Animals & Pet Supplies", "Fashion"],
  country_filter: ["Aland Islands", "American Samoa"],
  searchValue: ["Nike Webstore", "Bodyman"]
}

希望这有助于..:D

答案 1 :(得分:1)

尝试查看此模式是否适合您

(?:\?|&)(.+?)=([A-Z+%0-9]+)

Example here