0

我有以下网址:

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

此 url 包含许多作为数组发送的参数:

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

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

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)。

4

2 回答 2

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

于 2013-10-15T11:07:01.310 回答
1

试试看这个模式是否适合你

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

这里的例子

于 2013-10-15T10:19:08.193 回答