Adding a parameter to the URL with JavaScript

后端 未结 30 2574
刺人心
刺人心 2020-11-22 07:33

In a web application that makes use of AJAX calls, I need to submit a request but add a parameter to the end of the URL, for example:

Original URL:

30条回答
  •  春和景丽
    2020-11-22 08:15

    As best I can tell none of the above answers address the case where the query string contains parameters which are themselves an array and hence will appear more than once, e.g:

    http://example.com?sizes[]=a&sizes[]=b
    

    The following function is what I wrote to update document.location.search. It takes an array of key/value pair arrays as an argument and it will return a revised version of the latter which you can do whatever you'd like with. I'm using it like this:

    var newParams = [
        ['test','123'],
        ['best','456'],
        ['sizes[]','XXL']
    ];
    var newUrl = document.location.pathname + insertParams(newParams);
    history.replaceState('', '', newUrl);
    

    If the current url was:

    http://example.com/index.php?test=replaceme&sizes[]=XL

    This would get you

    http://example.com/index.php?test=123&sizes[]=XL&sizes[]=XXL&best=456

    Function

    function insertParams(params) {
        var result;
        var ii = params.length;
        var queryString = document.location.search.substr(1);
        var kvps = queryString ? queryString.split('&') : [];
        var kvp;
        var skipParams = [];
        var i = kvps.length;
        while (i--) {
            kvp = kvps[i].split('=');
            if (kvp[0].slice(-2) != '[]') {
                var ii = params.length;
                while (ii--) {
                    if (params[ii][0] == kvp[0]) {
                        kvp[1] = params[ii][1];
                        kvps[i] = kvp.join('=');
                        skipParams.push(ii);
                    }
                }
            }
        }
        var ii = params.length;
        while (ii--) {
            if (skipParams.indexOf(ii) === -1) {
                kvps.push(params[ii].join('='));
            }
        }
        result = kvps.length ? '?' + kvps.join('&') : '';
        return result;
    }
    

提交回复
热议问题