在一个使用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并查看每个参数,然后添加新参数或更新已经存在的值。
当前回答
我添加我的解决方案,因为它支持相对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');
});
});
其他回答
我有一个'类',这是:
function QS(){
this.qs = {};
var s = location.search.replace( /^\?|#.*$/g, '' );
if( s ) {
var qsParts = s.split('&');
var i, nv;
for (i = 0; i < qsParts.length; i++) {
nv = qsParts[i].split('=');
this.qs[nv[0]] = nv[1];
}
}
}
QS.prototype.add = function( name, value ) {
if( arguments.length == 1 && arguments[0].constructor == Object ) {
this.addMany( arguments[0] );
return;
}
this.qs[name] = value;
}
QS.prototype.addMany = function( newValues ) {
for( nv in newValues ) {
this.qs[nv] = newValues[nv];
}
}
QS.prototype.remove = function( name ) {
if( arguments.length == 1 && arguments[0].constructor == Array ) {
this.removeMany( arguments[0] );
return;
}
delete this.qs[name];
}
QS.prototype.removeMany = function( deleteNames ) {
var i;
for( i = 0; i < deleteNames.length; i++ ) {
delete this.qs[deleteNames[i]];
}
}
QS.prototype.getQueryString = function() {
var nv, q = [];
for( nv in this.qs ) {
q[q.length] = nv+'='+this.qs[nv];
}
return q.join( '&' );
}
QS.prototype.toString = QS.prototype.getQueryString;
//examples
//instantiation
var qs = new QS;
alert( qs );
//add a sinle name/value
qs.add( 'new', 'true' );
alert( qs );
//add multiple key/values
qs.add( { x: 'X', y: 'Y' } );
alert( qs );
//remove single key
qs.remove( 'new' )
alert( qs );
//remove multiple keys
qs.remove( ['x', 'bogus'] )
alert( qs );
我已经重写了toString方法,所以不需要调用QS::getQueryString,你可以使用QS::toString,或者像我在示例中所做的那样,仅仅依赖于对象被强制转换为字符串。
在URL类中有一个内置函数,你可以使用它来轻松处理查询字符串的键/值参数:
const url = new URL(window.location.href);
// url.searchParams has several function, we just use `set` function
// to set a value, if you just want to append without replacing value
// let use `append` function
url.searchParams.set('key', 'value');
console.log(url.search) // <== '?key=value'
// if window.location.href has already some qs params this `set` function
// modify or append key/value in it
有关searchParams函数的更多信息。
IE不支持URL,请检查兼容性
我喜欢穆罕穆德·法提赫·耶尔达兹的回答,即使他没有回答整个问题。
在他回答的同一行中,我使用了这样的代码:
“它不控制参数的存在,也不改变现有的值。它把你的参数加到最后"
/** add a parameter at the end of the URL. Manage '?'/'&', but not the existing parameters.
* does escape the value (but not the key)
*/
function addParameterToURL(_url,_key,_value){
var param = _key+'='+escape(_value);
var sep = '&';
if (_url.indexOf('?') < 0) {
sep = '?';
} else {
var lastChar=_url.slice(-1);
if (lastChar == '&') sep='';
if (lastChar == '?') sep='';
}
_url += sep + param;
return _url;
}
测试者:
/*
function addParameterToURL_TESTER_sub(_url,key,value){
//log(_url);
log(addParameterToURL(_url,key,value));
}
function addParameterToURL_TESTER(){
log('-------------------');
var _url ='www.google.com';
addParameterToURL_TESTER_sub(_url,'key','value');
addParameterToURL_TESTER_sub(_url,'key','Text Value');
_url ='www.google.com?';
addParameterToURL_TESTER_sub(_url,'key','value');
_url ='www.google.com?A=B';
addParameterToURL_TESTER_sub(_url,'key','value');
_url ='www.google.com?A=B&';
addParameterToURL_TESTER_sub(_url,'key','value');
_url ='www.google.com?A=1&B=2';
addParameterToURL_TESTER_sub(_url,'key','value');
}//*/
这将在所有现代浏览器中工作。
function insertParam(key,value) {
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' +key+'='+value;
window.history.pushState({path:newurl},'',newurl);
}
}
查看https://github.com/derek-watson/jsUri
Uri和javascript查询字符串操作。
这个项目结合了Steven Levithan的优秀parseUri正则表达式库。您可以安全地解析所有形状和大小的url,无论它们是多么无效或丑陋。