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

原始URL:

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

导致的网址:

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

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


当前回答

它处理这样的URL:

空 没有任何参数 已经有一些参数 有什么?在最后,但同时没有任何参数

它不处理这样的URL:

带有片段标识符(即散列,#) 如果URL已经有必要的查询参数(那么将会有重复)

适用于:

Chrome 32 + 火狐26 + 野生动物园7.1 +

function appendQueryParameter(url, name, value) {
    if (url.length === 0) {
        return;
    }

    let rawURL = url;

    // URL with `?` at the end and without query parameters
    // leads to incorrect result.
    if (rawURL.charAt(rawURL.length - 1) === "?") {
        rawURL = rawURL.slice(0, rawURL.length - 1);
    }

    const parsedURL = new URL(rawURL);
    let parameters = parsedURL.search;

    parameters += (parameters.length === 0) ? "?" : "&";
    parameters = (parameters + name + "=" + value);

    return (parsedURL.origin + parsedURL.pathname + parameters);
}

使用ES6模板字符串的版本。

适用于:

Chrome 41 + 火狐32 + 野生动物园9.1 +

function appendQueryParameter(url, name, value) {
    if (url.length === 0) {
        return;
    }

    let rawURL = url;

    // URL with `?` at the end and without query parameters
    // leads to incorrect result.
    if (rawURL.charAt(rawURL.length - 1) === "?") {
        rawURL = rawURL.slice(0, rawURL.length - 1);
    }

    const parsedURL = new URL(rawURL);
    let parameters = parsedURL.search;

    parameters += (parameters.length === 0) ? "?" : "&";
    parameters = `${parameters}${name}=${value}`;

    return `${parsedURL.origin}${parsedURL.pathname}${parameters}`;
}

其他回答

你需要适应的基本实现是这样的:

function insertParam(key, value) {
    key = encodeURIComponent(key);
    value = encodeURIComponent(value);

    // kvp looks like ['key1=value1', 'key2=value2', ...]
    var kvp = document.location.search.substr(1).split('&');
    let i=0;

    for(; i<kvp.length; i++){
        if (kvp[i].startsWith(key + '=')) {
            let pair = kvp[i].split('=');
            pair[1] = value;
            kvp[i] = pair.join('=');
            break;
        }
    }

    if(i >= kvp.length){
        kvp[kvp.length] = [key,value].join('=');
    }

    // can return this or...
    let params = kvp.join('&');

    // reload page with new params
    document.location.search = params;
}

这大约是正则表达式或基于搜索的解决方案的两倍,但这完全取决于查询字符串的长度和任何匹配的索引


为了完成起见,我以慢速regex方法为基准(大约慢了150%)

function insertParam2(key,value)
{
    key = encodeURIComponent(key); value = encodeURIComponent(value);

    var s = document.location.search;
    var kvp = key+"="+value;

    var r = new RegExp("(&|\\?)"+key+"=[^\&]*");

    s = s.replace(r,"$1"+kvp);

    if(!RegExp.$1) {s += (s.length>0 ? '&' : '?') + kvp;};

    //again, do what you will here
    document.location.search = s;
}

这是一个非常简化的版本,为了可读性和更少的代码行而不是微观优化的性能(我们说的是几毫秒的差异,实际上……由于它的性质(操作当前文档的位置),这将很可能在一个页面上运行一次)。

/**
* Add a URL parameter (or changing it if it already exists)
* @param {search} string  this is typically document.location.search
* @param {key}    string  the key to set
* @param {val}    string  value 
*/
var addUrlParam = function(search, key, val){
  var newParam = key + '=' + val,
      params = '?' + newParam;

  // If the "search" string exists, then build params from it
  if (search) {
    // Try to replace an existance instance
    params = search.replace(new RegExp('([?&])' + key + '[^&]*'), '$1' + newParam);

    // If nothing was replaced, then add the new param to the end
    if (params === search) {
      params += '&' + newParam;
    }
  }

  return params;
};

然后你可以这样使用:

document.location.pathname + addUrlParam(document.location.search, 'foo', 'bar');

好的,在这里我比较两个函数,一个由我自己(regExp)和另一个由(annakata)。

将数组:

function insertParam(key, value)
{
    key = escape(key); value = escape(value);

    var kvp = document.location.search.substr(1).split('&');

    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
    return "&"+kvp.join('&'); 
}

正则表达式的方法:

function addParameter(param, value)
{
    var regexp = new RegExp("(\\?|\\&)" + param + "\\=([^\\&]*)(\\&|$)");
    if (regexp.test(document.location.search)) 
        return (document.location.search.toString().replace(regexp, function(a, b, c, d)
        {
                return (b + param + "=" + value + d);
        }));
    else 
        return document.location.search+ param + "=" + value;
}

测试用例:

time1=(new Date).getTime();
for (var i=0;i<10000;i++)
{
addParameter("test","test");
}
time2=(new Date).getTime();
for (var i=0;i<10000;i++)
{
insertParam("test","test");
}

time3=(new Date).getTime();

console.log((time2-time1)+" "+(time3-time2));

似乎即使使用最简单的解决方案(当regexp只使用test而不输入.replace函数时),它仍然比分裂要慢…好。Regexp有点慢,但是…喔…

我添加我的解决方案,因为它支持相对url除了绝对url。在其他方面,它与顶部的答案相同,后者也使用Web API。

/**
 * updates a relative or absolute
 * by setting the search query with
 * the passed key and value.
 */
export const setQueryParam = (url, key, value) => {
  const dummyBaseUrl = 'https://dummy-base-url.com';
  const result = new URL(url, dummyBaseUrl);
  result.searchParams.set(key, value);
  return result.toString().replace(dummyBaseUrl, '');
};

还有人开玩笑说:

// some jest tests
describe('setQueryParams', () => {
  it('sets param on relative url with base path', () => {
    // act
    const actual = setQueryParam(
      '/', 'ref', 'some-value',
    );
    // assert
    expect(actual).toEqual('/?ref=some-value');
  });
  it('sets param on relative url with no path', () => {
    // act
    const actual = setQueryParam(
      '', 'ref', 'some-value',
    );
    // assert
    expect(actual).toEqual('/?ref=some-value');
  });
  it('sets param on relative url with some path', () => {
    // act
    const actual = setQueryParam(
      '/some-path', 'ref', 'some-value',
    );
    // assert
    expect(actual).toEqual('/some-path?ref=some-value');
  });
  it('overwrites existing param', () => {
    // act
    const actual = setQueryParam(
      '/?ref=prev-value', 'ref', 'some-value',
    );
    // assert
    expect(actual).toEqual('/?ref=some-value');
  });
  it('sets param while another param exists', () => {
    // act
    const actual = setQueryParam(
      '/?other-param=other-value', 'ref', 'some-value',
    );
    // assert
    expect(actual).toEqual('/?other-param=other-value&ref=some-value');
  });
  it('honors existing base url', () => {
    // act
    const actual = setQueryParam(
      'https://base.com', 'ref', 'some-value',
    );
    // assert
    expect(actual).toEqual('https://base.com/?ref=some-value');
  });
  it('honors existing base url with some path', () => {
    // act
    const actual = setQueryParam(
      'https://base.com/some-path', 'ref', 'some-value',
    );
    // assert
    expect(actual).toEqual('https://base.com/some-path?ref=some-value');
  });
});

感谢大家的贡献。我使用annakata代码并修改为也包括url中根本没有查询字符串的情况。 希望这能有所帮助。

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('&');
        }
    }