使用 JavaScript 向 URL 添加参数

编程入门 行业动态 更新时间:2024-10-14 08:22:59
本文介绍了使用 JavaScript 向 URL 添加参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在使用 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 添加参数

本文发布于:2023-11-26 02:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632271.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   JavaScript   URL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!