Saturday, November 26, 2011

Retrieving Query Strings in Javascript

Retrieving Query Strings in Javascript
Javascript can be used for retrieves query string values too. We need the following code to get query string pairs (field & value) using Javascript:
window.location.search
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/testjs2.htm?name=alma&role=user
The return value is ?name=alma&role=user
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: Page 1</title> <script lang=”javascript” type=”text/javascript”> function testQueryStrings() { // change the window.location with your own. window.location = “/…/testjs2.htm?name=alma&role=user”; } </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 testjs2.htm (of course with the specified query strings!). Here testjs.htm:
    <html> <head> <title>Test Query Strings: Page 2</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 testjs2.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.

No comments:

Post a Comment