Adding a parameter to the URL with JavaScript

后端 未结 30 2241
刺人心
刺人心 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 07:51

    /**
    * Add a URL parameter 
    * @param {string} url 
    * @param {string} param the key to set
    * @param {string} value 
    */
    var addParam = function(url, param, value) {
       param = encodeURIComponent(param);
       var a = document.createElement('a');
       param += (value ? "=" + encodeURIComponent(value) : ""); 
       a.href = url;
       a.search += (a.search ? "&" : "") + param;
       return a.href;
    }
    
    /**
    * Add a URL parameter (or modify if already exists)
    * @param {string} url 
    * @param {string} param the key to set
    * @param {string} value 
    */
    var addOrReplaceParam = function(url, param, value) {
       param = encodeURIComponent(param);
       var r = "([&?]|&)" + param + "\\b(?:=(?:[^&#]*))*";
       var a = document.createElement('a');
       var regex = new RegExp(r);
       var str = param + (value ? "=" + encodeURIComponent(value) : ""); 
       a.href = url;
       var q = a.search.replace(regex, "$1"+str);
       if (q === a.search) {
          a.search += (a.search ? "&" : "") + str;
       } else {
          a.search = q;
       }
       return a.href;
    }
    
    url = "http://www.example.com#hashme";
    newurl = addParam(url, "ciao", "1");
    alert(newurl);

    And please note that parameters should be encoded before being appended in query string.

    http://jsfiddle.net/48z7z4kx/

提交回复
热议问题