在一个使用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并查看每个参数,然后添加新参数或更新已经存在的值。
当前回答
好的,在这里我比较两个函数,一个由我自己(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 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 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;
}
}
});
随着JS的新成就,这里是如何将查询参数添加到URL:
var protocol = window.location.protocol,
host = '//' + window.location.host,
path = window.location.pathname,
query = window.location.search;
var newUrl = protocol + host + path + query + (query ? '&' : '?') + 'param=1';
window.history.pushState({path:newUrl}, '' , newUrl);
还有这种可能性Moziila URLSearchParams.append()
这将在所有现代浏览器中工作。
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);
}
}
这就是我在服务器端(如Node.js)添加或更新一些基本url参数时使用的方法。
CoffeScript:
### @method addUrlParam Adds parameter to a given url. If the parameter already exists in the url is being replaced. @param {string} url @param {string} key Parameter's key @param {string} value Parameter's value @returns {string} new url containing the parameter ### addUrlParam = (url, key, value) -> newParam = key+"="+value result = url.replace(new RegExp('(&|\\?)' + key + '=[^\&|#]*'), '$1' + newParam) if result is url result = if url.indexOf('?') != -1 then url.split('?')[0] + '?' + newParam + '&' + url.split('?')[1] else if url.indexOf('#') != -1 then url.split('#')[0] + '?' + newParam + '#' + url.split('#')[1] else url + '?' + newParam return result
JavaScript:
function addUrlParam(url, key, value) { var newParam = key+"="+value; var result = url.replace(new RegExp("(&|\\?)"+key+"=[^\&|#]*"), '$1' + newParam); if (result === url) { result = (url.indexOf("?") != -1 ? url.split("?")[0]+"?"+newParam+"&"+url.split("?")[1] : (url.indexOf("#") != -1 ? url.split("#")[0]+"?"+newParam+"#"+ url.split("#")[1] : url+'?'+newParam)); } return result; } var url = "http://www.example.com?foo=bar&ciao=3&doom=5#hashme"; result1.innerHTML = addUrlParam(url, "ciao", "1"); <p id="result1"></p>