7

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?

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

4 Comments

Not a single answer there will do what the OP is asking for (i.e., array detection in the query string).
You're right. I didn't realize - I just saw a complicated function and I thought something that complicated must do it right.. but it didn't. I added my version.
why not just post it instead of get?
If I could pick two answers I would. This answers what I really asked, Timothy's answers what I really needed.
1

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

4 Comments

Acutally yes, with getUrlParam that does return an array as I needed.
Because, as he just said... "actually yes, [my suggestion] does" do what he needed.
but then the query string is incompatible with the server software...?
@arnorhs - No, it was most likely that he didn't mean to add the "[]" when he was building his query string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.