PDA

View Full Version : Easy way to get Querystring vars


Thompson
03-19-2008, 08:09 PM
Hello, guys!

Here is a function to let easier the manipulation of Querystrings in Javascript:


function getObjUrlVars()
{
var objQstring = new Object();
var qString;
var pairKeyValue;
var key;
var value;
var i;

//queryString

qString = window.location.search.substr(1, window.location.search.length).split("&");

//making object with keys and values;
for( i=0; i<qString.length; i++ )
{
//get only existing variables.
pairKeyValue = qString[i].split("=");
key = pairKeyValue[0];
value = pairKeyValue[1];

if( key.length > 0 )
{
//stores variable in object
eval('objQstring.' + key + ' = "' + value + '"');
}

//cleaning variables for next iteration
pairKeyValue = "";
key = "";
value = "";
}

return objQstring;
}


Here is an example of its use: suppose that you have a link to some page like this: http://www.mypage.com?var1=a&var2=b&var3=c

Juse use the funcion to get Querystring variables:

var variables = getObjUrlVars();

alert(variables.var1);
alert(variables.var2);
alert(variables.var3);


Hope this can be useful. :)