在使用 AJAX 调用的 Web 应用程序中,我需要提交请求但在 URL 末尾添加一个参数,例如:
In a web application that makes use of AJAX calls, I need to submit a request but add a parameter to the end of the URL, for example:
原始网址:
server/myapp.php?id=10
结果网址:
server/myapp.php?id=10&启用=真
寻找一个 JavaScript 函数来解析 URL,查看每个参数,然后添加新参数或更新值(如果已经存在).
Looking for a JavaScript function which parses the URL looking at each parameter, then adds the new parameter or updates the value if one already exists.
推荐答案您需要调整的基本实现如下所示:
A basic implementation which you'll need to adapt would look something like this:
function insertParam(key, value) { key = encodeURIComponent(key); value = encodeURIComponent(value); // kvp looks like ['key1=value1', 'key2=value2', ...] var kvp = document.location.search.substr(1).split('&'); let i=0; for(; i<kvp.length; i++){ if (kvp[i].startsWith(key + '=')) { let pair = kvp[i].split('='); pair[1] = value; kvp[i] = pair.join('='); break; } } if(i >= kvp.length){ kvp[kvp.length] = [key,value].join('='); } // can return this or... let params = kvp.join('&'); // reload page with new params document.location.search = params; }这大约是基于正则表达式或基于搜索的解决方案的两倍,但这完全取决于查询字符串的长度和任何匹配项的索引
This is approximately twice as fast as a regex or search based solution, but that depends completely on the length of the querystring and the index of any match
我为了完成而进行基准测试的慢速正则表达式方法(大约慢 150%)
the slow regex method I benchmarked against for completions sake (approx +150% slower)
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; }更多推荐
使用 JavaScript 向 URL 添加参数
发布评论