Jquery reading several array parameters from url

和自甴很熟 提交于 2019-12-22 01:04:32

问题


I have the following 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

This url contains alot of paramters that are sent as an array:

Now i wish to get each individual array and its value out

in the above example the result should be something like this:

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'
);

is it possible to get it out like this and if so how? i have attempted with the following:

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

However this only returned 1 value (Nike Webstore) in my example.


回答1:


as parameters are an array. the below code will work just fine..

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

which will give us....

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

hope this helps.. :D




回答2:


Try to see if this pattern works for you

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

Example here



来源:https://stackoverflow.com/questions/19377617/jquery-reading-several-array-parameters-from-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!