Getting Querystring Values in Javascript.
Recently, I had to do a quick project wherein I had to quickly gain access to the querystring on an HTML page. I wasn't in a position where I could "rethink the architecture" at all, so I quickly wrote the following code. If you're in the same position, I hope you can use the following code:
function getQueryString() {
var rv = new Array();
var pw = window.parent;
while(pw.parent != pw)
{
pw = pw.parent;
}
var qs = new String(pw.location).split('?');
if(qs.length < 2)
{
return rv;
}
var kvPairs = qs[1].split('&');
for(var i = 0; i < kvPairs.length;i++)
{
var s = kvPairs[i].split('=');
var l = "";
for(var j = 1; j < s.length; j++)
{
l += s[j];
}
if(rv[s[0]] == null)
{
rv[s[0]] = new Array();
rv[s[0]][0] = l;
}
else
{
rv[s[0]][rv[s[0]].length] = l;
}
}
return rv; }
window.location.queryString = getQueryString();Place this code in your javascript, and viola, you have access to the querystring values via the new window.location.queryString object.
Now, assuming the following url: http://www.mysite.com/page.html?parameter=535426, you can quickly grab the query value via the following:
alert(window.location.queryString.parameter)Note... check for nulls here, because the object will be created depending on the querystring parameters passed to the page. Hence, if the parameter querystring key value isn't present, window.location.queryString.parameter will return null.
0 comments:
Post a Comment