gpt4 book ai didi

javascript - 在 FreeMarker 上获取 URL 的 queryString 参数的更好方法

转载 作者:行者123 更新时间:2023-12-04 08:11:23 30 4
gpt4 key购买 nike

关闭。这个问题是opinion-based .它目前不接受答案。












想改善这个问题吗?更新问题,以便可以通过 editing this post 用事实和引文回答问题.

7 个月前关闭。




Improve this question




有没有更好的方法来读取 FreeMarker 上的查询字符串参数值,我有一个 URL,例如:http://test.com/user?testp1=123&testp2=2541我创建了下面的函数来读取这些查询参数:
脚本

function testParams() {
const params = new URLSearchParams(window.location.search);
const testp1 = params.get('testp1');
const testp2 = params.get('testp2');
document.getElementById("testp1").value = testp1;
document.getElementById("testp2").value = testp2;

}
window.onload = testParams;
<input type="text" name="testp1" id="testp1" />
<input type="text" name="testp2" id="testp2" />

因此,当页面加载时,它会读取这些查询参数并将它们设置为各自的字段。

最佳答案

遍历所有参数并检索键和值:

function testParams() {
// Demo hardcoded string, you use window.location.search
const params = new URLSearchParams("testp1=123&testp2=2541");
[...params].forEach(([key, val]) => document.getElementById(key).value = val);
}
window.addEventListener("load", testParams);
<input type="text" name="testp1" id="testp1" />
<input type="text" name="testp2" id="testp2" />

另外,请阅读: URLSearchParams.entries()

关于javascript - 在 FreeMarker 上获取 URL 的 queryString 参数的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65938912/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com