Get URL array variables in javascriptjquery - Stack Overflow

I've got a bunch of parameters being passed to a page by URL variables.The URL looks sort of lik

I've got a bunch of parameters being passed to a page by URL variables. The URL looks sort of like:

file.aspx?category[]=1&category[]=7&category[]=3&id=8az

Using the jQuery getUrlParam extension I can get url variables very easily, but rather than returning category as an array (which is what I want) it gets returned as null.

Is there a way for me to read these into a javascript array?

I've got a bunch of parameters being passed to a page by URL variables. The URL looks sort of like:

file.aspx?category[]=1&category[]=7&category[]=3&id=8az

Using the jQuery getUrlParam extension I can get url variables very easily, but rather than returning category as an array (which is what I want) it gets returned as null.

Is there a way for me to read these into a javascript array?

Share Improve this question asked Feb 10, 2011 at 22:55 HibiscusHibiscus 5924 silver badges11 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

I previously pointed to this question: Get QueryString values with jQuery - but as @Crescent Fresh pointed out, those examples don't deal with arrays in the query string (and besides, they're a bit slow I think.

So I cooked up my version of this function:

function getQueryString () {
    var ret = {};
    var parts = (document.location.toString().split('?')[1]).split('&');
    for (var i = 0; i < parts.length; i++) {

        var p = parts[i].split('=');
        // so strings will be correctly parsed:
        p[1] = decodeURIComponent(p[1].replace(/\+/g, " "));

        if (p[0].search(/\[\]/) >= 0) { // then it's an array
            p[0] = p[0].replace('[]','');

            if (typeof ret[p[0]] != 'object') ret[p[0]] = [];
            ret[p[0]].push(p[1]);
        } else {
            ret[p[0]] = p[1];
        }
    }
    return ret;
}

But there are caveats. It will only work on a correctly formed query string - there's no error detection. Also, it does not work on numbered/indexed arrays.. that is when your array is defined in the query string as:

?category[3]=1&category[4]=7&category[20]=3&id=8az

It would be trivial to add to the .search() query a regex for finding that as well, but I'm not the best regex expert... anybody got ideas?

Shouldn't it be: file.aspx?category=1&category=7&category=3

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744362672a4570547.html

相关推荐

  • Get URL array variables in javascriptjquery - Stack Overflow

    I've got a bunch of parameters being passed to a page by URL variables.The URL looks sort of lik

    7天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信