Adding a parameter to the URL with JavaScript

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

    Vianney Bajart's answer is correct; however, URL will only work if you have the complete URL with port, host, path and query:

    new URL('http://server/myapp.php?id=10&enabled=true')
    

    And URLSearchParams will only work if you pass only the query string:

    new URLSearchParams('?id=10&enabled=true')
    

    If you have an incomplete or relative URL and don't care for the base URL, you can just split by ? to get the query string and join later like this:

    function setUrlParams(url, key, value) {
      url = url.split('?');
      usp = new URLSearchParams(url[1]);
      usp.set(key, value);
      url[1] = usp.toString();
      return url.join('?');
    }
    
    let url = 'myapp.php?id=10';
    url = setUrlParams(url, 'enabled', true);  // url = 'myapp.php?id=10&enabled=true'
    url = setUrlParams(url, 'id', 11);         // url = 'myapp.php?id=11&enabled=true'
    

    Not compatible with Internet Explorer.

提交回复
热议问题