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()]): '';
   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 {
    for (var Qn in Request._qrysArr) {
     _Sp_Each = Request._qrysArr[Qn].split("=");
     Request._QryColl[_Sp_Each[0].toLowerCase()] = _Sp_Each[1];
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 :

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

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
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
 var x=Request.QueryString();

this will alert all the querystring values as a string. like the following
Things to remember:
1.The Request Object and all the Functions are case, you cannot use "request.querystring()". It should be always

No comments:

Post a Comment