Retrieving Query Strings in Javascript

The query string is composed of a series of field – value pair. Below is the pattern of query string:
field1=value1&field2=value2&field3=value3

An URL that contains query string can be depicted as follow:
http://TestFile.com/tag?name=Rajiv&role=Administrator
The URL and query string separated by a question mark (?). Query string consist of two parts (field and value), and each of pair separated by ampersand (&). So the example above consists of two query strings which are name and type with value of each field ‘Rajiv’ and ‘Administrator’ respectively.

Javascript can be used for retrieves query string values too. We need the following code to get query string pairs (field & value) using Javascript:

The above code will return string started with ampersand in the URL (ampersand included). So if we run the above code against the following URL: http://localhost:8088/postings/QrStr/TestFile.htm?name=Rajiv&role=Administrator
The return value is ?name=Rajiv&role=Administrator

To understand the concept better I have write two simple HTML pages that show how to get query string values using Javascript. This is the first file (testqrstr.htm):

<html>
<head>
<title>Test Query Strings: Index Page </title>
<script lang=”javascript” type=”text/javascript”>
function testQueryStrings()
{
// change the window.location with your own.
window.location = “/…/TestFile.htm?name=Rajiv&role=Administrator”;
}
</script>
</head>
<body>
<input type=”button” id=”btn” value=”Test Query Strings” onclick=”testQueryStrings()” />
</body>
</html>

The output produced by testjs.htm is similar like the output of Test.aspx, when we click the button it will bring us to TestFile.htm (of course with the specified query strings!). Here testjs.htm:

<html>
<head>
<title>Test Query Strings: Final Page</title>
<script lang=”javascript” type=”text/javascript”>
var qrStr = window.location.search;
var spQrStr = qrStr.substring(1);
var arrQrStr = new Array();
// splits each of pair
var arr = spQrStr.split(’&’);

for (var i=0;i<arr.length;i++){
// splits each of field-value pair
var index = arr[i].indexOf(’=');
var key = arr[i].substring(0,index);
var val = arr[i].substring(index+1);

// saves each of field-value pair in an array variable
arrQrStr[key] = val;
}

document.write(”<h1>Name parameter: “+arrQrStr["name"]+”. Role parameter: “+arrQrStr["role"]+”</h1>”);
</script>
</head>
<body>
</body>
</html>

What I was did in TestFile.htm just retrieve the query strings (through window.location.search), save each of field – value pair in an array variable named arrQrStr and echo the content of arrQrStr variable.
Tags: , ,
Hot on Web:


About author