Tuesday, September 24, 2013

Retrieve query string parameter values in Javascript


Below is the Javascript code to fetch the query string parameter values from the URL.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
function buttonClick() {

    var _QS = getQueryString();

    if (_QS['data'] == 'service') {
        // Service logic here
    }
    else if (_QS['data'] == 'sales') {
        // Sales logic here
    }
}

function getQueryString() {

    var _queryString = {};
    var _query = window.location.search.substring(1);
    
    // Split the parameters
    var _vars = _query.split("&");

    for (var i = 0; i < _vars.length; i++) {

        // Split the Name & Value pair
        var _pair = _vars[i].split("=");

        if (typeof _queryString[_pair[0]] === "undefined") {
            _queryString[_pair[0]] = _pair[1];

        } else if (typeof _queryString[_pair[0]] === "string") {
            var _array = [_queryString[_pair[0]], _pair[1]];
            _queryString[_pair[0]] = _array;

        } else {
            _queryString[_pair[0]].push(_pair[1]);
        }
    }

    return _queryString;
}

No comments:

Post a Comment