在使用AJAX调用的Web应用程序中,我需要提交一个请求,但要在URL的末尾添加一个参数, 寻找一种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('&'); }
这大约是正则表达式或基于搜索的解决方案的两倍,但是这完全取决于查询字符串的长度和任何匹配项的索引
我为完成测试而基准的慢速正则表达式方法(慢了大约+ 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; }