使用 JavaScript 通过 window.location.search 属性获取 URL 传递的值,查询字符串以 ? 开头。解析查询字符串:使用 URLSearchParams 对象(例如 var params = new URLSearchParams(searchParams);),使用 get() 方法获取值(例如 console.log(params.get("name"));),确保解码查询字符串为 UTF-8 格式。

如何使用 JavaScript 获取 URL 传递的值
在 JavaScript 中,可以使用 window.location.search 属性获取 URL 传递的值。该属性返回一个包含查询字符串的字符串,即 URL 中问号 (?) 之后的部分。
打开方式:
<code class="javascript">var searchParams = window.location.search;</code>
示例:
<code class="html"><a href="index.html?name=John&age=30">获取值</a></code>
JavaScript 代码:
<code class="javascript">var searchParams = window.location.search; console.log(searchParams); // 输出:?name=John&age=30</code>
解析查询字符串:
要解析查询字符串并获取各个值,可以使用 URLSearchParams 对象:
<code class="javascript">var params = new URLSearchParams(searchParams);
console.log(params.get("name")); // 输出:John
console.log(params.get("age")); // 输出:30</code>注意:
window.location.search 将返回一个空字符串。URLSearchParams 对象将返回一个数组。以上就是js如何获取url传递的值的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号