Thought Patterns

Cameron’s thoughts on everything and nothing.

Emulate PHP’s $_GET in JavaScript

| 0 comments

I’m currently developing a JavaScript picture gallery widget / web service and needed a way to access GET parameters that I’ve passed via one page to another. This is simple in PHP as you can just access the $_GET super global array. Well I did a bit of searching on the internet and found a snippet of code to achieve the same thing in JavaScript.

var $_GET = [];
var vars_area = location.search.substring(1);
if(vars_area.length > 2)
{
var get_sets = vars_area.split('&');
for(i = 0, k = get_sets.length; i < k; i++)
{
var parts = get_sets[i].split('=');
$_GET[unescape(parts[0])] = unescape(parts[1]);
}
}

Stick the above code in the head section of your page (within script tags) or at the top of an external JavaScript file. You’ll then have a very useful $_GET array which contains all your GET params and their associated values.

Bookmark and Share

Leave a Reply

Required fields are marked *.

*