Adding a parameter to the URL with JavaScript

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

    Try this.

    // uses the URL class
    function setParam(key, value) {
                let url = new URL(window.document.location);
                let params = new URLSearchParams(url.search.slice(1));
    
                if (params.has(key)) {
                    params.set(key, value);
                }else {
                    params.append(key, value);
                }
            }
    

提交回复
热议问题