在一个使用AJAX调用的web应用程序中,我需要提交一个请求,但在URL的末尾添加一个参数,例如:

原始URL:

http://server/myapp.php?id=10

导致的网址:

http://server/myapp.php?id=10&enabled=true

寻找一个JavaScript函数,该函数解析URL并查看每个参数,然后添加新参数或更新已经存在的值。


当前回答

/** * 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);

请注意,参数应该在被追加到查询字符串之前进行编码。

http://jsfiddle.net/48z7z4kx/

其他回答

我是这么做的。使用我的editParams()函数,你可以添加,删除或更改任何参数,然后使用内置的replaceState()函数更新URL:

window.history.replaceState('object or string', 'Title', 'page.html' + editParams('enable', 'true'));


// background functions below:

// add/change/remove URL parameter
// use a value of false to remove parameter
// returns a url-style string
function editParams (key, value) {
  key = encodeURI(key);

  var params = getSearchParameters();

  if (Object.keys(params).length === 0) {
    if (value !== false)
      return '?' + key + '=' + encodeURI(value);
    else
      return '';
  }

  if (value !== false)
    params[key] = encodeURI(value);
  else
    delete params[key];

  if (Object.keys(params).length === 0)
    return '';

  return '?' + $.map(params, function (value, key) {
    return key + '=' + value;
  }).join('&');
}

// Get object/associative array of URL parameters
function getSearchParameters () {
  var prmstr = window.location.search.substr(1);
  return prmstr !== null && prmstr !== "" ? transformToAssocArray(prmstr) : {};
}

// convert parameters from url-style string to associative array
function transformToAssocArray (prmstr) {
  var params = {},
      prmarr = prmstr.split("&");

  for (var i = 0; i < prmarr.length; i++) {
    var tmparr = prmarr[i].split("=");
    params[tmparr[0]] = tmparr[1];
  }
  return params;
}

试一试 正则表达式,如此之慢,因此:

var SetParamUrl = function(_k, _v) {// replace and add new parameters

    let arrParams = window.location.search !== '' ? decodeURIComponent(window.location.search.substr(1)).split('&').map(_v => _v.split('=')) : Array();
    let index = arrParams.findIndex((_v) => _v[0] === _k); 
    index = index !== -1 ? index : arrParams.length;
    _v === null ? arrParams = arrParams.filter((_v, _i) => _i != index) : arrParams[index] = [_k, _v];
    let _search = encodeURIComponent(arrParams.map(_v => _v.join('=')).join('&'));

    let newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + (arrParams.length > 0 ? '?' +  _search : ''); 

    // window.location = newurl; //reload 

    if (history.pushState) { // without reload  
        window.history.pushState({path:newurl}, null, newurl);
    }

};

var GetParamUrl = function(_k) {// get parameter by key

    let sPageURL = decodeURIComponent(window.location.search.substr(1)),
        sURLVariables = sPageURL.split('&').map(_v => _v.split('='));
    let _result = sURLVariables.find(_v => _v[0] === _k);
    return _result[1];

};

例子:

        // https://some.com/some_path
        GetParamUrl('cat');//undefined
        SetParamUrl('cat', "strData");// https://some.com/some_path?cat=strData
        GetParamUrl('cat');//strData
        SetParamUrl('sotr', "strDataSort");// https://some.com/some_path?cat=strData&sotr=strDataSort
        GetParamUrl('sotr');//strDataSort
        SetParamUrl('cat', "strDataTwo");// https://some.com/some_path?cat=strDataTwo&sotr=strDataSort
        GetParamUrl('cat');//strDataTwo
        //remove param
        SetParamUrl('cat', null);// https://some.com/some_path?sotr=strDataSort

以下几点:

合并重复的查询字符串参数 使用绝对和相对url 在浏览器和节点中工作

/**
 * Adds query params to existing URLs (inc merging duplicates)
 * @param {string} url - src URL to modify
 * @param {object} params - key/value object of params to add
 * @returns {string} modified URL
 */
function addQueryParamsToUrl(url, params) {

    // if URL is relative, we'll need to add a fake base
    var fakeBase = !url.startsWith('http') ? 'http://fake-base.com' : undefined;
    var modifiedUrl = new URL(url || '', fakeBase);

    // add/update params
    Object.keys(params).forEach(function(key) {
        if (modifiedUrl.searchParams.has(key)) {
            modifiedUrl.searchParams.set(key, params[key]);
        }
        else {
            modifiedUrl.searchParams.append(key, params[key]);
        }
    });

    // return as string (remove fake base if present)
    return modifiedUrl.toString().replace(fakeBase, '');
}

例子:

// returns /guides?tag=api
addQueryParamsToUrl('/guides?tag=hardware', { tag:'api' })

// returns https://orcascan.com/guides?tag=api
addQueryParamsToUrl('https://orcascan.com/guides?tag=hardware', { tag: 'api' })
const params = new URLSearchParams(window.location.search);

params.delete(key)
window.history.replaceState({}, "", decodeURIComponent(`${window.location.pathname}?${params}`));

这是一个添加查询参数的简单方法:

const query = new URLSearchParams(window.location.search);
query.append("enabled", "true");

这就是这里更多的内容。

请注意支持规格。