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 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With