在使用AJAX调用的Web应用程序中,我需要提交请求,但在URL的末尾添加一个参数,例如:
原始网址:
HTTP://server/myapp.php ID = 10
结果URL:
http://server/myapp.php?id = 10 &enabled = true
寻找一个解析每个参数的URL的JavaScript函数,然后添加新参数或更新值(如果已存在).
您可以使用以下方法之一:
https://developer.mozilla.org/en-US/docs/Web/API/URL
https://developer.mozilla.org/en/docs/Web/API/URLSearchParams
例:
var url = new URL("http://foo.bar/?x=1&y=2"); // If your expected result is "http://foo.bar/?x=1&y=2&x=42" url.searchParams.append('x', 42); // If your expected result is "http://foo.bar/?x=42&y=2" url.searchParams.set('x', 42);
您需要适应的基本实现看起来像这样:
function insertParam(key, value) { key = encodeURI(key); value = encodeURI(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 document.location.search = kvp.join('&'); }
这大约是正则表达式或基于搜索的解决方案的两倍,但这完全取决于查询字符串的长度和任何匹配的索引
为了完成而我使用慢速正则表达式进行基准测试(大约慢了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; }
谢谢大家的贡献.我使用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('&'); } }
这是非常简单的解决方案.它不控制参数存在,也不改变现有值.它将您的参数添加到end,因此您可以在后端代码中获取最新值.
function addParameterToURL(param){ _url = location.href; _url += (_url.split('?')[1] ? '&':'?') + param; return _url; }
这是一个非常简化的版本,为了易读性和更少的代码行而不是微优化的性能进行权衡(我们正在谈论几毫秒的差异,实际上......由于其性质(在当前文档的位置上运行) ),这很可能会在页面上运行一次).
/** * 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');
/**
* 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);
我有一个'类'来做这个,这里是:
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的字符串,你想用param装饰,你可以试试这个:
urlstring += ( urlstring.match( /[\?]/g ) ? '&' : '?' ) + 'param=value';
这意味着什么?将是参数的前缀,但如果你已经有?in urlstring
,than &将成为前缀.
encodeURI( paramvariable )
如果你没有硬编码参数,我也会建议做,但它在里面paramvariable
; 或者如果你有滑稽的角色.
有关该功能的使用,请参阅javascript URL编码encodeURI
.
这是添加查询参数的简单方法:
const query = new URLSearchParams(window.location.search); query.append("enabled", "true");
这就是更多.
请注意支持规格.
查看https://github.com/derek-watson/jsUri
Uri和javascript中的查询字符串操作。
该项目包含了Steven Levithan出色的parseUri正则表达式库。您可以安全地解析各种形状和大小的URL,但是这些URL无效或令人生厌。
有时我们?
在最后的URL 看到,我发现了一些产生结果的解决方案file.php?&foo=bar
.我按照自己的意愿完成了自己的解决方案工作!
location.origin + location.pathname + location.search + (location.search=='' ? '?' : '&') + 'lang=ar'
注意:location.origin在IE中不起作用,这是它的修复.