Adding a parameter to the URL with JavaScript

后端 未结 30 2287
刺人心
刺人心 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:02

    Thank you all for your contribution. I used annakata code and modified to also include the case where there is no query string in the url at all. Hope this would help.

    function insertParam(key, value) {
            key = escape(key); value = escape(value);
    
            var kvp = document.location.search.substr(1).split('&');
            if (kvp == '') {
                document.location.search = '?' + key + '=' + value;
            }
            else {
    
                var i = kvp.length; var x; while (i--) {
                    x = kvp[i].split('=');
    
                    if (x[0] == key) {
                        x[1] = value;
                        kvp[i] = x.join('=');
                        break;
                    }
                }
    
                if (i < 0) { kvp[kvp.length] = [key, value].join('='); }
    
                //this will reload the page, it's likely better to store this until finished
                document.location.search = kvp.join('&');
            }
        }
    

提交回复
热议问题