在一个使用AJAX调用的web应用程序中,我需要提交一个请求,但在URL的末尾添加一个参数,例如:
原始URL:
http://server/myapp.php?id=10
导致的网址:
http://server/myapp.php?id=10&enabled=true
寻找一个JavaScript函数,该函数解析URL并查看每个参数,然后添加新参数或更新已经存在的值。
在一个使用AJAX调用的web应用程序中,我需要提交一个请求,但在URL的末尾添加一个参数,例如:
原始URL:
http://server/myapp.php?id=10
导致的网址:
http://server/myapp.php?id=10&enabled=true
寻找一个JavaScript函数,该函数解析URL并查看每个参数,然后添加新参数或更新已经存在的值。
当前回答
加入@Vianney的回答https://stackoverflow.com/a/44160941/6609678
我们可以导入node中的内置URL模块,如下所示
const { URL } = require('url');
例子:
Terminal $ node
> const { URL } = require('url');
undefined
> let url = new URL('', 'http://localhost:1989/v3/orders');
undefined
> url.href
'http://localhost:1989/v3/orders'
> let fetchAll=true, timePeriod = 30, b2b=false;
undefined
> url.href
'http://localhost:1989/v3/orders'
> url.searchParams.append('fetchAll', fetchAll);
undefined
> url.searchParams.append('timePeriod', timePeriod);
undefined
> url.searchParams.append('b2b', b2b);
undefined
> url.href
'http://localhost:1989/v3/orders?fetchAll=true&timePeriod=30&b2b=false'
> url.toString()
'http://localhost:1989/v3/orders?fetchAll=true&timePeriod=30&b2b=false'
有用的链接:
https://developer.mozilla.org/en-US/docs/Web/API/URL https://developer.mozilla.org/en/docs/Web/API/URLSearchParams
其他回答
好的,在这里我比较两个函数,一个由我自己(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有点慢,但是…喔…
var MyApp = new Class();
MyApp.extend({
utility: {
queryStringHelper: function (url) {
var originalUrl = url;
var newUrl = url;
var finalUrl;
var insertParam = function (key, value) {
key = escape(key);
value = escape(value);
//The previous post had the substr strat from 1 in stead of 0!!!
var kvp = newUrl.substr(0).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('=');
}
finalUrl = kvp.join('&');
return finalUrl;
};
this.insertParameterToQueryString = insertParam;
this.insertParams = function (keyValues) {
for (var keyValue in keyValues[0]) {
var key = keyValue;
var value = keyValues[0][keyValue];
newUrl = insertParam(key, value);
}
return newUrl;
};
return this;
}
}
});
以下几点:
合并重复的查询字符串参数 使用绝对和相对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' })
就我所知,上面的答案都没有解决查询字符串包含参数的情况,这些参数本身就是一个数组,因此会出现不止一次,例如:
http://example.com?sizes[]=a&sizes[]=b
下面的函数是我用来更新document.location.search的。它接受一个键/值对数组作为参数,它将返回一个修改后的版本,你可以做任何你想做的事情。我是这样使用的:
var newParams = [
['test','123'],
['best','456'],
['sizes[]','XXL']
];
var newUrl = document.location.pathname + insertParams(newParams);
history.replaceState('', '', newUrl);
如果当前url为:
http://example.com/index.php?test=replaceme&sizes [] = XL
这会让你
http://example.com/index.php?test=123&sizes[]=XL&尺寸[]=XXL&best=456
函数
function insertParams(params) {
var result;
var ii = params.length;
var queryString = document.location.search.substr(1);
var kvps = queryString ? queryString.split('&') : [];
var kvp;
var skipParams = [];
var i = kvps.length;
while (i--) {
kvp = kvps[i].split('=');
if (kvp[0].slice(-2) != '[]') {
var ii = params.length;
while (ii--) {
if (params[ii][0] == kvp[0]) {
kvp[1] = params[ii][1];
kvps[i] = kvp.join('=');
skipParams.push(ii);
}
}
}
}
var ii = params.length;
while (ii--) {
if (skipParams.indexOf(ii) === -1) {
kvps.push(params[ii].join('='));
}
}
result = kvps.length ? '?' + kvps.join('&') : '';
return result;
}
Vianney Bajart的答案是正确的;然而,URL只会工作,如果你有完整的URL端口,主机,路径和查询:
new URL('http://server/myapp.php?id=10&enabled=true')
URLSearchParams只会在你只传递查询字符串时起作用:
new URLSearchParams('?id=10&enabled=true')
如果你有一个不完整或相对的URL,不关心的基础URL,你可以通过?获取查询字符串,然后像这样连接:
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'
Internet Explorer浏览器不兼容。