Pages

Feb 8, 2010

How to access queryStrings in client side + JavaScript

This question is mostly asked by people because there may be situations where we could make use of QueryStrings in the clientside.
So how to proceed with this?

There are two options to do this
1. Make use of HiddenField and store the queryString in a hidden field in the Page_Load and access it from the client side.
But this is an indirect way where we have to use more server controls to store and retrive the data which may have some performance impact. So lets find some other way to access the queryString from the Clienside directly.
2. Make use of the JavaScript Magic to Access the QueryString directly like
Say For eg.
We are passing a querysting named customerID in a url.
eg.  http://www.xxx.com/test.aspx?customerID=007
Then the CustomerID is the key which we could pass to the below method to get the value(007) of the querystring.

function getQuerystring(key, default_)
{

if (default_==null) default_="";

key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,\\\]);

var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");

var qs = regex.exec(window.location.href);
if(qs == null)

return default_;

else

return qs[1];

}
 
The output is 007.

No comments: