22/7/10

JavaSript to get query string items

I wanted to make my own function in order to get the query string items. The code below initializes an array which will contain queryStringItem objects, with properties name and value. So if the text in the address bar is
http://www.blogger.com/post-create.g?blogID=6495603084419766846
the code will return an array of length 1, which will store an object of type queryStringItem whose name property will be equal to blogID and value property equal to 6495603084419766846.

The code was tested in Internet Explorer 8.0.7600 and Mozilla FireFox 3.5.10

function getQueryStringItemArray() {

    //Check if there is a query string
    if (location.search.length > 0) {
       
        //Initialize the Array which will store the queryStringItem Objects
        var queryArray = new Array();
       
        //Get the query string and ommit the ? charqacter
        var queryString = location.search.replace("?", "");

        //Devide the query string into its components (name = value) and store them all in an Array
        //so that each Array slot contains a name = value string
        var queryStringItems = queryString.split("&");

        //Create the queryStringObject for every name = value string created above
        //Push every queryStringObject into the queryArray, so that each slot contains a
        //queryStringObject with properties name and value
        for (var indexOfQueryStringItems = 0; indexOfQueryStringItems < queryStringItems.length; indexOfQueryStringItems++) {
            queryArray.push(createQueryStringItem(queryStringItems[indexOfQueryStringItems]));
        }
    }

    return queryArray;
}

function createQueryStringItem(someString) {
   
    var queryStringItem = new Object();
   
    var queryStringItemParts = someString.split("=");
   
    queryStringItem.name = decodeURIComponent(queryStringItemParts[0]);
   
    queryStringItem.value = decodeURIComponent(queryStringItemParts[1]);

    return queryStringItem;
}

Δεν υπάρχουν σχόλια:

Δημοσίευση σχολίου