在一个使用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并查看每个参数,然后添加新参数或更新已经存在的值。
当前回答
我有一个'类',这是:
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,或者像我在示例中所做的那样,仅仅依赖于对象被强制转换为字符串。
其他回答
重置所有查询字符串
Var params = {params:"val1", params:"val2"}; 让str = jQuery.param(参数); let uri = window.location. reff . tostring (); if (uri.indexOf("?") > 0) Uri = Uri。substring (0, uri.indexOf(“?”); console.log (uri +”?”+ str); / / window.location。Href = uri+"?"+str; < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < /脚本>
试一试 正则表达式,如此之慢,因此:
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
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;
}
}
});
const params = new URLSearchParams(window.location.search);
params.delete(key)
window.history.replaceState({}, "", decodeURIComponent(`${window.location.pathname}?${params}`));
这是一个非常简化的版本,为了可读性和更少的代码行而不是微观优化的性能(我们说的是几毫秒的差异,实际上……由于它的性质(操作当前文档的位置),这将很可能在一个页面上运行一次)。
/**
* 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');