Sunday, 18 December 2011

Get Query String from Javascript

In this tutorial you will se how to get query string values using javascript.
function getQueryString()  
{  
    var vars = [], hash;  
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');  
    for(var i = 0; i < hashes.length; i++)  
    {  
        hash = hashes[i].split('=');  
        vars.push(hash[0]);  
        vars[hash[0]] = hash[1];  
    }  
    return vars;  
}  
Let's suppose we have the following URL
http://www.mysite/home.aspx?id=1&name=test
Calling getQueryString() function would return you the following array:
{  
    "id"    : "1",  
    "name" : "test"  
}
To get the value of parameters you will do this.
var id= getQueryString()["id"];  
var name= getQueryString()["name"];  

Hope this tutorial will help you.

No comments:

Post a Comment