使用JavaScript将参数添加到URL在使用AJAX调用的Web应用程序中,我需要提交请求,但在URL的末尾添加一个参数,例如:原始网址:HTTP://server/myapp.php ID = 10结果URL:http://server/myapp.php?id = 10 &enabled = true寻找一个解析每个参数的URL的JavaScript函数,然后添加新参数或更新值(如果已存在)。
3 回答
交互式爱情
TA贡献1712条经验 获得超3个赞
您需要适应的基本实现看起来像这样:
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;}
喵喵时光机
TA贡献1846条经验 获得超7个赞
谢谢大家的贡献。我使用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('&'); } }
添加回答
举报
0/150
提交
取消