gpt4 book ai didi

javascript - 使用 Javascript 获取 URL Vars,当 QueryString 中存在多个值时不起作用

转载 作者:行者123 更新时间:2023-11-30 09:08:23 25 4
gpt4 key购买 nike

我正在使用 Javascript 函数获取 URL 的值并使用以下函数传递给 jQuery:

 function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}

然后像这样设置值:

 var type = getUrlVars()["type"]

这一切都完美无缺,但是我刚刚遇到需要获取多个值的情况,我的表单元素之一是可以检查多个值的复选框,所以我的 URL 看起来像这样:

 http://www.domain.com/test.php?type=1&cuisine[]=23&cuisine[]=43&name=test

如果我使用上面的函数提醒 cuisine 值,我只会得到最终值:

 alert (getUrlVars()["cuisine[]"]);

会提醒“43”。

我希望它是所有“美食”值的逗号分隔字符串。即在上面的例子中“23,43”

非常欢迎任何帮助!如果任何解决方案需要它,我正在使用 PHP 5.3 和 Jquery 1.4

最佳答案

    function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');

if($.inArray(hash[0], vars)>-1)
{
vars[hash[0]]+=","+hash[1];
}
else
{
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
}

return vars;
}

关于javascript - 使用 Javascript 获取 URL Vars,当 QueryString 中存在多个值时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2849415/

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