【问题标题】:Jquery reading several array parameters from urljQuery从url读取几个数组参数
【发布时间】:2013-10-15 09:25:53
【问题描述】:

我有以下网址:

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

【问题讨论】:

  • 我刚刚做了一个快速的代码来做你想做的事....但我还没有测试过..尝试更改变量“url”,看看它是否有效......这里是链接...jsbin.com/UYILAzU/2/edit?js,console
  • @PsychHalf 测试它是否挂起:D
  • 好的..那么测试怎么样了??
  • @PsychHalf 刚刚完成,完美时您可以将其发布为答案吗?

标签: javascript jquery arrays urldecode


【解决方案1】:

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

// 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

【讨论】:

    【解决方案2】:

    试试这个模式是否适合你

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

    Example here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多