gpt4 book ai didi

javascript - 获取url参数: How to convert URL specific parameters to array?

转载 作者:行者123 更新时间:2023-12-03 02:27:25 25 4
gpt4 key购买 nike

如何将url特定参数转换为数组?我使用过很多类型或参数。我已尝试使用以下代码 var types = ['A', 'C']; 及其工作原理。

但它不适用于 url。我需要从 URL 获取 community 参数。如何将url参数转换为数组?像这样 var types = ['business_center','wireless_access'];

http://demo/apartments/?price-min=200&price-max=2356&bedroom=3&bathroom=2&ap_features%5B%5D=washer+%26+dryer+connections&ap_features%5B%5D=dishwasher&community%5B%5D=business_center&community%5B%5D=clubhouse&community%5B%5D=covered_parking&submit=SEARCH

//var types = ['A', 'C'];
var i = document.location.href.lastIndexOf('?');
document.location.href.substr(i+1).replace(/community=/g,'').split('&');
$('input[name="community[]"]').prop('checked', function() {
return $.inArray(this.value, types) !== -1;
});

最佳答案

您可以拆分 URL 并从中创建 JSON 对象。参数将成为键,它们的值将存储在相应的数组中。

var url = 'http://demo/apartments/?price-min=200&price-max=2356&bedroom=3&bathroom=2&ap_features%5B%5D=washer+%26+dryer+connections&ap_features%5B%5D=dishwasher&community%5B%5D=business_center&community%5B%5D=clubhouse&community%5B%5D=covered_parking&submit=SEARCH';

var ob = URLToArray(url);
console.log(ob); //output the whole key-value pair object
console.log(ob["community"]); //obtain the "community" values (Array)

function URLToArray(url) {
var request = {};
var pairs = url.substring(url.indexOf('?') + 1).split('&');
for (var i = 0; i < pairs.length; i++) {
if (!pairs[i]) //if empty parameter then continue to next
continue;
var pair = pairs[i].split('='); //split to separate values
if (pair[0].indexOf('%') > -1) //community has some string attached to it starting with %, this cleans it
pair[0] = pair[0].substring(0, (pair[0].indexOf('%')));
var key = pair[0];
if (key in request) //check if any value with same key is already stored
request[key].push(pair[1]); //append to the array of already existing values
else
request[key] = [pair[1]]; //else make a new key-value pair, value is an array of elements
}
return request;
}

关于javascript - 获取url参数: How to convert URL specific parameters to array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48885578/

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