使用Javascript获取URL变量,当QueryString中存在多个值时不起作用 [英] Using Javascript to get URL Vars, not working when multiple values present in QueryString

查看:72
本文介绍了使用Javascript获取URL变量,当QueryString中存在多个值时不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using a Javascript function to get the values of a URL to pass to jQuery using the function below:

 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看起来像这样:

This all works perfectly, however I have just come into a situation where I need to get multiple values, one of my form elements are checkboxes where multiple values can be checked, so my URL will look something like this:

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

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

If I alert out the cuisine value using the function above I only ever get the final value:

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

会警告"43".

我希望它是所有"cuisine"值的逗号分隔字符串.即在上面的示例"23,43"

What I would like it to be is a comma delimited string of all "cuisine" values. ie in the above example "23,43"

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

Any help very welcome! In case any solution requires it I am using PHP 5.3 and 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获取URL变量,当QueryString中存在多个值时不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆