Javascript jQuery从URL中的哈希读取参数并存储在对象中
是否有jquery的扩展可从一组参数中获取:Javascript jQuery从URL中的哈希读取参数并存储在对象中,javascript,jquery,jquery-plugins,Javascript,Jquery,Jquery Plugins,是否有jquery的扩展可从一组参数中获取: categories[]=Shop+Mac&categories[]=Software&price_max=2799&price_min=24&sort=&page=1 JSON对象,如: { 'categories': ["Shop Mac", "Software"], 'price_max': "2799", 'price_min': "24", 'page':
categories[]=Shop+Mac&categories[]=Software&price_max=2799&price_min=24&sort=&page=1
JSON对象,如:
{
'categories': ["Shop Mac", "Software"],
'price_max': "2799",
'price_min': "24",
'page': '1'
}
…?我在一个类似的问题中写了一个函数,应该对您有所帮助。我投票结束了这个问题,因为这是一个重复的问题,但现在我看到在这个问题上有额外的要求。当我写下这个答案时,我制作了一个版本,它也可以处理数组样式的URL参数:
(function () {
var e,
d = function (s) { return decodeURIComponent(s).replace(/\+/g, " "); },
q = window.location.search.substring(1),
r = /([^&=]+)=?([^&]*)/g;
while (e = r.exec(q)) {
if (e[1].indexOf("[") == "-1")
urlParams[d(e[1])] = d(e[2]);
else {
var b1 = e[1].indexOf("["),
aN = e[1].slice(b1+1, e[1].indexOf("]", b1)),
pN = d(e[1].slice(0, b1));
if (typeof urlParams[pN] != "object")
urlParams[d(pN)] = {},
urlParams[d(pN)].length = 0;
if (aN)
urlParams[d(pN)][d(aN)] = d(e[2]);
else
Array.prototype.push.call(urlParams[d(pN)], d(e[2]));
}
}
})();
您可以在此处看到一个工作演示:
示例查询字符串:
test=Hello&person[]=jeff&person[]=jim&person[extra]=john&nocache=1290122355841
结果:
{
"test": "Hello",
"person": {
"0": "jeff",
"1": "jim",
"length": 2,
"extra": "john"
},
"nocache": "1290100673882"
}
我有一个简单的解决方案:
// Get args from somewhere
var args = 'categories[]=Shop+Mac&categories[]=Software&price_max=2799&price_min=24&sort=&page=1';
// Set up final object
var output = {}
// Split on & to get groups of key-value pairs
args = args.split('&');
for (i = 0; i < args.length; i++) {
// Split on = to get separate key from value
args[i] = args[i].split('=');
// Remove square brackets from the key if they exist
if (/\[\]$/.test(args[i][0])) {
key = args[i][0].substring(0,(args[i][0].length) - 2);
} else {
key = args[i][0]
}
// If we haven't visited this key before then set it to a empty array
if (output[key] === undefined) {
output[key] = [];
}
// Push the value in to the array and remove + symbols whilst we're at it
output[key].push(args[i][1].replace('+', ' '));
}
您将得到:
categories: ["Shop Mac", "Software"]
page: ["1"]
price_max: ["2799"]
price_min: ["24"]
sort: [""]
重复:请注意,此解决方案不解码结果(它只是将
+
转换为空格)。我不知道+
符号的意义是什么,但我看到输出将其删除,所以我也这样做了。修改此解决方案以在此时执行任何您想要的操作都是很容易的。
categories: ["Shop Mac", "Software"]
page: ["1"]
price_max: ["2799"]
price_min: ["24"]
sort: [""]