使用JavaScript为URL添加参数

在使用AJAX调用的Web应用程序中,我需要提交请求,但在URL的末尾添加一个参数,例如:

原始url:

HTTP://server/myapp.php ID = 10

结果url:

http://server/myapp.php?id = 10 &enabled = true

寻找一个JavaScript函数来分析查看每个参数的URL,然后添加新的参数或者更新已经存在的值。

你需要适应的基本实现看起来像这样:

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('&'); } 

这大约是正则expression式或基于search的解决scheme的两倍,但完全取决于查询string的长度和任何匹配的索引


为了达到完整的目的,我使用了缓慢的正则expression式方法(约慢了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中根本没有查询string的情况。 希望这会有所帮助。

 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('&'); } } 

这是非常简单的解决scheme。 它不控制参数的存在,也不改变现有的值。 它将您的参数添加到结尾,以便您可以在后端代码中获得最新的值。

 function addParameterToURL(param){ _url = location.href; _url += (_url.split('?')[1] ? '&':'?') + param; return _url; } 

这是一个大大简化的版本,为了易于理解和less量代码而不是微型优化的性能(我们正在谈论几个毫秒的差异,现实的折中…由于其性质(在当前文档的位置),这很可能会在页面上运行一次)。

 /** * 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'); 

我有一个“class”这样做,这里是:

 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,或者像我在示例中所做的那样仅仅依靠被强制转换成string的对象。

使用:

例:

 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); 
 /** * Add a URL parameter * @param {url} string url * @param {param} string the key to set * @param {value} 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 {url} string url * @param {param} string the key to set * @param {value} string value */ var addOrReplaceParam = function(url, param, value) { param = encodeURIComponent(param); var r = "([&?]|&amp;)" + 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); 

请注意参数在被追加到查询string之前应该被编码。

http://jsfiddle.net/48z7z4kx/

有时我们看到? 在最后的URL,我发现了一些解决scheme,产生的结果为file.php?&foo=bar 。 我想出了我自己的解决scheme,完美无缺!

 location.origin + location.pathname + location.search + (location.search=='' ? '?' : '&') + 'lang=ar' 

注意: location.origin在IE中不起作用, 这里是它的修复 。

如果你有一个string的url,你想用param装饰,你可以试试这个:

 urlstring += ( urlstring.match( /[\?]/g ) ? '&' : '?' ) + 'param=value'; 

这意味着 将是参数的前缀,但是如果你已经有了urlstring ,比将成为前缀。

我也build议做encodeURI( paramvariable )如果你没有硬编码的参数,但它是一个paramvariable ; 或者如果你有有趣的人物。

请参阅javascript URL编码以使用encodeURI函数。

看看https://github.com/derek-watson/jsUri

Uri和javascript中的查询string操作。

这个项目包含了Steven Levithan出色的parseUri正则expression式库。 您可以安全地parsing所有形状和大小的URL,但是无效或可怕。

这就是我使用的一些基本的url参数添加或更新在服务器端像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 

这是我自己的尝试,但我会用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; } 

此外,我从另一个post上find了这个jQuery插件,如果你需要更多的灵活性,你可以使用它: http : //plugins.jquery.com/project/query-object

我会认为代码将(未testing):

 return $.query.parse(sourceUrl).set(parameterName, parameterValue).toString(); 

我会用这个小而完整的图书馆来处理js中的url:

https://github.com/Mikhus/jsurl

这是添加查询参数的简单方法:

 const query = new URLSearchParams(window.location.search); query.append("enabled", "true"); 

这就是更多

谢谢,T04435

我喜欢穆罕默德·法提赫·耶尔德兹的答案,即使他没有回答整个问题。

在他的回答中,我使用这个代码:

“它不控制参数的存在,也不改变现有的值,它将你的参数添加到最后”

  /** 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; } 

和testing者:

  /* 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将帮助您添加,更新和删除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 

//例题

 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

 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; } 

好吧,我在这里比较两个函数,一个是我自己制作的(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('&'); } 

正则expression式方法:

 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; } 

testing案例:

 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)); 

看来,即使用最简单的解决scheme(当正则expression式只使用testing,不进入.replace函数),它仍然比分裂慢…好吧。 正则expression式有点慢,但是…呃…

如果你在链接或其他地方搞垃圾邮件,你也可能需要考虑哈希值。 这是一个相当简单易懂的解决scheme。 可能不是最快,因为它使用正则expression式…但在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; } } 

这是我做的。 使用我的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; } 

我能想到的最简单的解决方法是这个方法,它将返回修改的URI。 我觉得你们大多数人工作太辛苦了。

 function setParam(uri, key, val) { return uri .replace(new RegExp("([?&]"+key+"(?=[=&#]|$)[^#&]*|(?=#|$))"), "&"+key+"="+encodeURIComponent(val)) .replace(/^([^?&]+)&/, "$1?"); } 

最好,我可以告诉上述答案都没有解决查询string包含参数本身是一个数组,因此会出现不止一次的情况,例如:

 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); 

如果当前url是:

http://example.com/index.php?test=replaceme&sizes[]=XL

这会得到你

http://example.com/index.php?test=123&sizes[]=XL&sizes[]=XXL&best=456

function

 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; } 

Eziest的解决scheme,如果你已经有一个标签,它会自动删除它,所以它不会一直添加相同的标签,玩得开心

 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; } 

然后

 changeURL("i=updated"); 

尝试
正则expression式很慢,因此:

 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; } } });