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

Better way of getting queryString params of a URL on FreeMarker

有没有更好的方法来读取 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()