在使用AJAX调用的Web应用程序中,我需要提交请求,但在URL的末尾添加一个参数,例如:
原始网址:
生成的网址:
http://server/myapp.php?id=10的&安培;当使能=真
寻找一个解析每个参数的URL的JavaScript函数,然后添加新参数或更新值(如果已经存在)。
答案 0 :(得分:171)
您需要适应的基本实现看起来像这样:
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;
}
答案 1 :(得分:154)
您可以使用以下方法之一:
示例:
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);
答案 2 :(得分:61)
谢谢大家的贡献。我使用了 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('&');
}
}
答案 3 :(得分:53)
这是一个非常简单的解决方案。它不控制参数存在,也不改变现有值。它将您的参数添加到end,因此您可以在后端代码中获取最新值。
function addParameterToURL(param){
_url = location.href;
_url += (_url.split('?')[1] ? '&':'?') + param;
return _url;
}
答案 4 :(得分:33)
这是一个非常简化的版本,为了易读性和更少的代码行而不是微优化的性能进行权衡(我们正在谈论几毫秒的差异,实际上......由于其性质(在当前文档的位置),这很可能会在页面上运行一次。)
/**
* 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');
答案 5 :(得分:20)
/**
* 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);
请注意,参数应在追加查询字符串之前进行编码。
答案 6 :(得分:19)
我有一个'类'来做这个,这里是:
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,或者我在示例中所做的只是依赖于被强制转换为字符串的对象。
答案 7 :(得分:7)
如果你有一个带有url的字符串,你想用param装饰,你可以试试这个:
urlstring += ( urlstring.match( /[\?]/g ) ? '&' : '?' ) + 'param=value';
这意味着 ? 将成为参数的前缀,但如果您已经有 ? urlstring
,而 &amp; 将成为前缀。
如果您没有硬编码参数,我还建议您encodeURI( paramvariable )
,但它位于paramvariable
内;或者如果你有滑稽的角色。
有关encodeURI
功能的使用情况,请参阅javascript URL Encoding。
答案 8 :(得分:6)
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 functions
的更多信息。
答案 9 :(得分:6)
这是添加查询参数的简单方法:
const query = new URLSearchParams(window.location.search);
query.append("enabled", "true");
就是more here。
请注意support specs。
答案 10 :(得分:6)
有时我们在结束网址上看到?
,我找到了一些生成file.php?&foo=bar
结果的解决方案。我按照自己的意愿完成了自己的解决方案工作!
location.origin + location.pathname + location.search + (location.search=='' ? '?' : '&') + 'lang=ar'
注意: location.origin 无法在IE浏览器here is its fix中使用。
答案 11 :(得分:4)
查看https://github.com/derek-watson/jsUri
Uri并在javascript中查询字符串操作。
该项目融合了Steven Levithan的优秀parseUri正则表达式库。您可以安全地解析所有形状和大小的URL,无论这些URL是无效还是可怕。
答案 12 :(得分:3)
它处理这样的URL:
?
,但同时没有任何参数它不处理这样的URL:
适用于:
function appendQueryParameter(url, name, value) {
if (url.length === 0) {
return;
}
let rawURL = url;
// URL with `?` at the end and without query parameters
// leads to incorrect result.
if (rawURL.charAt(rawURL.length - 1) === "?") {
rawURL = rawURL.slice(0, rawURL.length - 1);
}
const parsedURL = new URL(rawURL);
let parameters = parsedURL.search;
parameters += (parameters.length === 0) ? "?" : "&";
parameters = (parameters + name + "=" + value);
return (parsedURL.origin + parsedURL.pathname + parameters);
}
带有ES6模板字符串的版本。
适用于:
function appendQueryParameter(url, name, value) {
if (url.length === 0) {
return;
}
let rawURL = url;
// URL with `?` at the end and without query parameters
// leads to incorrect result.
if (rawURL.charAt(rawURL.length - 1) === "?") {
rawURL = rawURL.slice(0, rawURL.length - 1);
}
const parsedURL = new URL(rawURL);
let parameters = parsedURL.search;
parameters += (parameters.length === 0) ? "?" : "&";
parameters = `${parameters}${name}=${value}`;
return `${parsedURL.origin}${parsedURL.pathname}${parameters}`;
}
答案 13 :(得分:3)
这是我在服务器端添加或更新一些基本url param时使用的,如Node.js。
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
&#13;
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");
&#13;
<p id="result1"></p>
&#13;
答案 14 :(得分:3)
以下功能将帮助您向URL添加,更新和删除参数
//例1
var myURL = '/search';
myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?location=california
myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?location=new%20york
myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search
//示例2
var myURL = '/search?category=mobile';
myURL = updateUrl(myURL,'location','california');
console.log('added location...' + myURL);
//added location.../search?category=mobile&location=california
myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?category=mobile&location=new%20york
myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search?category=mobile
//示例3
var myURL = '/search?location=texas';
myURL = updateUrl(myURL,'location','california');
console.log('updated location...' + myURL);
//added location.../search?location=california
myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?location=new%20york
myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search
//范例4
var myURL = '/search?category=mobile&location=texas';
myURL = updateUrl(myURL,'location','california');
console.log('updated location...' + myURL);
//added location.../search?category=mobile&location=california
myURL = updateUrl(myURL,'location','new york');
console.log('updated location...' + myURL);
//updated location.../search?category=mobile&location=new%20york
myURL = updateUrl(myURL,'location');
console.log('removed location...' + myURL);
//removed location.../search?category=mobile
这是函数
function updateUrl(url,key,value){
if(value!=undefined){
value = encodeURI(value);
}
var urls = url.split('?');
var baseUrl = urls[0];
var parameters = '';
var outPara = {};
if(urls.length>1){
parameters = urls[1];
}
if(parameters!=''){
parameters = parameters.split('&');
for(k in parameters){
var keyVal = parameters[k];
keyVal = keyVal.split('=');
var ekey = keyVal[0];
var eval = '';
if(keyVal.length>1){
eval = keyVal[1];
}
outPara[ekey] = eval;
}
}
if(value!=undefined){
outPara[key] = value;
}else{
delete outPara[key];
}
parameters = [];
for(var k in outPara){
parameters.push(k + '=' + outPara[k]);
}
var finalUrl = baseUrl;
if(parameters.length>0){
finalUrl += '?' + parameters.join('&');
}
return finalUrl;
}
答案 15 :(得分:2)
我会选择this小而完整的库来处理js中的网址:
答案 16 :(得分:2)
这是我自己的尝试,但我会使用annakata的答案,因为它似乎更清洁:
function AddUrlParameter(sourceUrl, parameterName, parameterValue, replaceDuplicates)
{
if ((sourceUrl == null) || (sourceUrl.length == 0)) sourceUrl = document.location.href;
var urlParts = sourceUrl.split("?");
var newQueryString = "";
if (urlParts.length > 1)
{
var parameters = urlParts[1].split("&");
for (var i=0; (i < parameters.length); i++)
{
var parameterParts = parameters[i].split("=");
if (!(replaceDuplicates && parameterParts[0] == parameterName))
{
if (newQueryString == "")
newQueryString = "?";
else
newQueryString += "&";
newQueryString += parameterParts[0] + "=" + parameterParts[1];
}
}
}
if (newQueryString == "")
newQueryString = "?";
else
newQueryString += "&";
newQueryString += parameterName + "=" + parameterValue;
return urlParts[0] + newQueryString;
}
另外,我从stackoverflow上的另一篇文章中找到了这个jQuery插件,如果你需要更多的灵活性,你可以使用它: http://plugins.jquery.com/project/query-object
我认为代码会(尚未测试):
return $.query.parse(sourceUrl).set(parameterName, parameterValue).toString();
答案 17 :(得分:2)
最简单的解决方案,如果你已经有标签就可以使用,并自动将其删除,以便它不会继续添加相同的标签,玩得开心
function changeURL(tag)
{
if(window.location.href.indexOf("?") > -1) {
if(window.location.href.indexOf("&"+tag) > -1){
var url = window.location.href.replace("&"+tag,"")+"&"+tag;
}
else
{
var url = window.location.href+"&"+tag;
}
}else{
if(window.location.href.indexOf("?"+tag) > -1){
var url = window.location.href.replace("?"+tag,"")+"?"+tag;
}
else
{
var url = window.location.href+"?"+tag;
}
}
window.location = url;
}
THEN
changeURL("i=updated");
答案 18 :(得分:2)
我喜欢MehmetFatihYıldız的答案,即使他没有回答整个问题。
与他的答案在同一行,我使用这段代码:
“它不控制参数存在,并且它不会改变现有值。它会将您的参数添加到结尾”
/** 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');
}//*/
答案 19 :(得分:1)
我能想到的最简单的解决方案是这个方法,它将返回修改后的URI。我觉得你们大多数人都在努力工作。
function setParam(uri, key, val) {
return uri
.replace(new RegExp("([?&]"+key+"(?=[=&#]|$)[^#&]*|(?=#|$))"), "&"+key+"="+encodeURIComponent(val))
.replace(/^([^?&]+)&/, "$1?");
}
答案 20 :(得分:1)
Vianney Bajart's answer是正确的;但是,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不兼容。
答案 21 :(得分:1)
尝试一下。
// uses the URL class
function setParam(key, value) {
let url = new URL(window.document.location);
let params = new URLSearchParams(url.search.slice(1));
if (params.has(key)) {
params.set(key, value);
}else {
params.append(key, value);
}
}
答案 22 :(得分:1)
如果你在链接或其他地方搞乱网址,你可能也必须考虑哈希。这是一个相当简单易懂的解决方案。可能不是 FASTEST ,因为它使用正则表达式...但在99.999%的情况下,差异真的无关紧要!
function addQueryParam( url, key, val ){
var parts = url.match(/([^?#]+)(\?[^#]*)?(\#.*)?/);
var url = parts[1];
var qs = parts[2] || '';
var hash = parts[3] || '';
if ( !qs ) {
return url + '?' + key + '=' + encodeURIComponent( val ) + hash;
} else {
var qs_parts = qs.substr(1).split("&");
var i;
for (i=0;i<qs_parts.length;i++) {
var qs_pair = qs_parts[i].split("=");
if ( qs_pair[0] == key ){
qs_parts[ i ] = key + '=' + encodeURIComponent( val );
break;
}
}
if ( i == qs_parts.length ){
qs_parts.push( key + '=' + encodeURIComponent( val ) );
}
return url + '?' + qs_parts.join('&') + hash;
}
}
答案 23 :(得分:0)
最好我可以告诉上述答案都不解决查询字符串包含本身就是数组的参数的情况,因此会出现不止一次,例如:
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);
如果当前网址是:
http://example.com/index.php?test=replaceme&sizes[]=XL
这会让你
http://example.com/index.php?test=123&sizes[]=XL&sizes[]=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;
}
答案 24 :(得分:0)
好的,我在这里比较两个函数,一个由我自己制作(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('&');
}
Regexp方法:
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仅使用测试而不进入.replace函数时)它仍然比分裂慢......嗯。 Regexp有点慢但是......呃......
答案 25 :(得分:0)
<强>尝试强>
正则表达式如此缓慢,因此:
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
答案 26 :(得分:0)
这里有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()
答案 27 :(得分:0)
这适用于所有现代浏览器。
class Fish {
private:
// TODO: declare any private member variables/functions here
char* m_memory;
int m_used, m_capa;
bool m_full;
std::string m_name;
}; //left out public stuff cuz It's posted up there
class Butterflyfish :public Fish {
private:
struct OBBY //for obnoxious
{
char letter = ' ';
int times = 0;
};
OBBY* m_extended;
int m_exCapa;
int m_exUsed;
};
答案 28 :(得分:0)
添加到@Vianney的答案https://stackoverflow.com/a/44160941/6609678
我们可以在节点中导入内置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
答案 29 :(得分:0)
const urlParams = new URLSearchParams(window.location.search);
urlParams.set('order', 'date');
window.location.search = urlParams;
.set第一个agrument是键,第二个是值。
答案 30 :(得分:0)
重置所有查询字符串
var params = { params1:"val1", params2:"val2" };
let str = jQuery.param(params);
let uri = window.location.href.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"></script>
答案 31 :(得分:-1)
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;
}
}
});
答案 32 :(得分:-1)
这是我的工作。使用我的editParams()函数,您可以添加,删除或更改任何参数,然后使用内置的replaceState()函数来更新URL:
window.history.replaceState('object or string', 'Title', 'page.html' + editParams('enable', 'true'));
// background functions below:
// add/change/remove URL parameter
// use a value of false to remove parameter
// returns a url-style string
function editParams (key, value) {
key = encodeURI(key);
var params = getSearchParameters();
if (Object.keys(params).length === 0) {
if (value !== false)
return '?' + key + '=' + encodeURI(value);
else
return '';
}
if (value !== false)
params[key] = encodeURI(value);
else
delete params[key];
if (Object.keys(params).length === 0)
return '';
return '?' + $.map(params, function (value, key) {
return key + '=' + value;
}).join('&');
}
// Get object/associative array of URL parameters
function getSearchParameters () {
var prmstr = window.location.search.substr(1);
return prmstr !== null && prmstr !== "" ? transformToAssocArray(prmstr) : {};
}
// convert parameters from url-style string to associative array
function transformToAssocArray (prmstr) {
var params = {},
prmarr = prmstr.split("&");
for (var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params;
}