Accessing querystring parameters on the client side - Hendrik Swanepoel

Hendrik Swanepoel

Accessing querystring parameters on the client side

I hate mixing server side code into my javascript code. It's messy and it doesn't allow me to store my javscript in separate .js files.

I had to get access to certain querystring parameters from my client side code, so I decided to write a reusable javascript object to access the whole querystring collection.

//this is to store the key value pairs of the querystring    
function qsObject(){
    this.objects = new Array();
    this.add = _add;
    this.remove =_remove;
    this.item = _item;
    this.populateCollection =_populateCollection;
    this.setRawString = _setRawString;
    this.rawString ="";
    
    this.setRawString();
    this.populateCollection();
    
    // to add items to the array
    function _add(obj){
        this.objects[this.objects.length] = obj;
    }
    //to remove items from the array
    function _remove(index){
        this.objects.splice(index, 1);
    }
    //gets a reference to an item object
    function _item(searchKey){
        searchKey = new String(searchKey);
        searchKey = searchKey.toLowerCase();
        for(i=0;i<this.objects.length;i++){
            //the current key in the coll
            var key = this.objects[i].key;
            key = new String(key);
            key = key.toLowerCase();
            
            if(key == searchKey){
                return this.objects[i];
            }
        }
    }
    
    function _setRawString(){
        //Create regular expression object to retrieve the qs part
        // Used regex 'cause the search property on the location object includes the bookmark stuff
        var qsReg = new RegExp("[?][^#]*","i");  
        hRef = unescape( window.location.href);
        var qsMatch = hRef.match(qsReg);  
        //removes the question mark from the url 
        qsMatch = new String(qsMatch);
        qsMatch = qsMatch.substr(1, qsMatch.length -1);        
        this.rawString = qsMatch;        
    }
    
    //takes a string and populates the array with the key/value pairs
    function _populateCollection(rawString){
        this.rawString = new String(this.rawString);
        var rootArr = this.rawString.split("&");
        for(i=0;i<rootArr.length;i++){
            var tempArr =  rootArr[i].split("=");
            if(tempArr.length ==2){
                tempArr[0] = unescape(tempArr[0]);
                tempArr[1] = unescape(tempArr[1]);
                
                this.add(new qsValue(tempArr[0], tempArr[1]));
            }
        }
    }
    
    function qsValue(key, value){
        this.key = key;
        this.value=value;    
    }     
}    
//example of using the object 
var qs= new qsObject();
var idObj= qs.item("id");
alert(idObj.key + " == " + idObj.value);


       

            
    

Comments

Colin said:

I just had a look at this code after reading your later post. I'm a bit rusty but surely it would be far simpler to just assign the name-value pairs as properties of the object, because the base "object" acts as a dynamic dictionary anyway?
i.e.
this.key = value;
# March 8, 2004 1:33 PM

Hendrik said:

Maybe I'm misinterpreting your comment.

I do this with the qsValue object :

function qsValue(key, value){
this.key = key;
this.value=value;
}

The qsObject simulates the QueryString collection in a way that it can retrieve items from it based on the key - the item it retrieves is an instance of the qsValue object.

Do you mean that I shouldn't have provided instantiation parameters for the object (key and value), but rather set it directly when the need arises?

I know this is possible, but it makes for much easier reading when you can see what the "fields" are for the object - especially in an example?

Hope I understood your comment correctly!
# March 8, 2004 1:51 PM

Colin said:

This probably isn't very clear but here goes. The QSObject populates it's member variables in the constructor. If you wanted to access the values as a list, you could always add a numeric indexer to the object that returns each name, and using that name get the value.

function QSObject(querystring){
//Create regular expression object to retrieve the qs part
// Used regex 'cause the search property on the location object includes the bookmark stuff
var qsReg = new RegExp("[?][^#]*","i");
hRef = unescape(querystring);
var qsMatch = hRef.match(qsReg);
//removes the question mark from the url
qsMatch = new String(qsMatch);
qsMatch = qsMatch.substr(1, qsMatch.length -1);
//split it up
var rootArr = qsMatch.split("&");
for(i=0;i<rootArr.length;i++){
var tempArr = rootArr[i].split("=");
if(tempArr.length ==2){
tempArr[0] = unescape(tempArr[0]);
tempArr[1] = unescape(tempArr[1]);

this[tempArr[0]]= tempArr[1];
}
}
}

//Sample usage
var b = new QSObject("http://yayaa?id=bbb&bob=ccc");
alert(b["id"]);
alert(b["bob"]);
//or
alert(b.id);
alert(b.bob);
# March 8, 2004 2:21 PM

Hendrik said:

Interesting! I see what you mean and I like it :)
How would you loop through the dynamic dictionary's items?

I have tried this:

<script>
function customObject(){
for(i=0;i<10;i++){
this["field" + i] = "value" + i;
}

}

var bla = new customObject();

alert(bla.field1); // yields "value1"

//the bla.length property is undefined, so the following yields nothing
for(i=0;i<bla.length;i++){
alert(bla["field" + i]);
}

//also undefined - due to difference in case
alert(bla["Field1"]);
</script>

The only thing that bothers me (only a little ;-) ) about this solution, is that the key lookup will then be case sensitive, while the server querystring collection's lookup isn't.

Thanks for the tip! Very useful.
# March 8, 2004 2:59 PM

TrackBack said:

# March 8, 2004 3:02 PM

Colin said:

....
if(tempArr.length ==2){
tempArr[0] = unescape(tempArr[0]);
tempArr[1] = unescape(tempArr[1]);

this[tempArr[0]]= tempArr[1];
//-> add next line
this[i] = tempArr[0];
....

If you look at the spec for v1.1+ items added in this way can be accessed by numeric index or by key (but the values must be added that way).

The above additional line will allow you to access the sample above like this:
var j = 0;
while (b[j] != undefined){
alert(b[j] + " == " + b[b[j]]);
j++;
}

To effect the case insensitive lookup you could just lowercase the key before you [add | access] the value. This method also will perform better because you are creating less objects and not looping through the array for every lookup.

Have fun :-)
# March 8, 2004 4:21 PM

Simon Stewart said:

I wrote up a short article for CodeProject on the exact same thing a while back:
http://www.codeproject.com/jscript/jscriptquerystring.asp

Although I haven't used the code in some time, it's really useful.
# March 10, 2004 5:58 PM

Girish Singh said:

Another article I found which explains a JavaScript code to do access Get Parameters.

<a href="www.mabaloo.com/.../a>

# May 3, 2008 8:54 PM

The Accidental Geek said:

Passing parameters to JavaScript files

# August 22, 2008 2:07 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: