Friday, November 27, 2009

Getting the query string in JavaScript and HTML

Getting the query string in JavaScript and HTML



Ever thought about having Query strings for HTML pages ? or even getting the query string values in JavaScript.
Here is one  JavaScript implementation of the "Request Object" that can retrieve the query string values.Currently only getting the query string values are possible.
For this we need to include the following script in the html page
Code :
var Request = {
 _winhref : '',
 _qrys : '',
 _qrysArr : [],
 _QryColl : [],
 QueryString : function(Qname) {
  if (Qname)
   return Request._QryColl[Qname.toLowerCase()]? (Request._QryColl[Qname.toLowerCase()]): '';
  else
   return _qrys;
 },
 Init : function() {
  _winhref = window.location.href;
  if (_winhref.indexOf("?") > -1) {
   _qrys = _winhref.split("?")[1];
   if (_qrys.length > 0) {
    if (_qrys.indexOf("&") > -1) {
     Request._qrysArr = _qrys.split("&");
    } else {
     Request._qrysArr.push(_qrys);
    }
    for (var Qn in Request._qrysArr) {
     _Sp_Each = Request._qrysArr[Qn].split("=");
     Request._QryColl[_Sp_Each[0].toLowerCase()] = _Sp_Each[1];
    }
   }
  }
 }
};
Request.Init();
Either this script can be put in  a seperate .js file and include in the HTML page . Or it can be directly put inside the script Tag.
Here is one sample HTML Page code :

<html>
 <head>
 <script src="Serverfunctions.js"></script>
 </head>
 <body>
  <script>
    var x=Request.QueryString("Qstr");
    alert(x);
  </script>
 </body>
</html>


The Serverfunctions.js is the file which has the Request Object code.Which will be under the same directory where the HTML page is.
I saved the page as Test.html . Now we will test our sample.
Open the HTML page in browser with some querystrings, let it be like this
Test.html?QStr=1&Y=2&Z=3
This will alert the value of "QStr".
(Note: the QueryString name is not case sensitive. even if we give "QSTR" instead of "QStr" , it will work )
Similarly, We can use the "Request.QueryString()" to see all the Querystrings available
So if we slightly modify the script like this in our HTML page
<script>
 var x=Request.QueryString();
 alert(x);
</script>

this will alert all the querystring values as a string. like the following
"QStr=1&Y=2&Z=3"
Things to remember:
1.The Request Object and all the Functions are case sensitive.ie, you cannot use "request.querystring()". It should be always
"Request.QueryString()"



No comments:

Post a Comment