gpt4 book ai didi

javascript - Jquery从url读取几个数组参数

转载 作者:行者123 更新时间:2023-11-28 20:14:42 26 4
gpt4 key购买 nike

我有以下网址:

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

最佳答案

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

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

关于javascript - Jquery从url读取几个数组参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19377617/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com