You need to enable JavaScript to run this app. 如何将URLSearchParams提取的表单数据渲染为两列HTML表格
优惠活动
大模型
产品
解决方案
定价
更多

如何将URLSearchParams提取的表单数据渲染为两列HTML表格

问题原因

  1. append()方法传入字符串时会默认作为纯文本节点插入,不会解析为HTML标签,所以你拼接的<th>、<td>都会直接显示为文本。
  2. 表格结构不符合规范:<td>、<th>必须嵌套在<tr>(行标签)内才能正常渲染,不能直接插入到<table>标签下,也不需要额外加<br>换行。
  3. 你更新后的代码存在无效的冗余语法('<th>code</th></tr>'));),会直接导致JS运行报错。

修正后完整代码

<table id="opresults">
    <caption>Survey Form</caption>
    <tr>
       <th>Form question</th>
       <th>Answer</th>
    </tr>
</table>

<script>
const resultsTable = document.getElementById('opresults');
new URLSearchParams(window.location.search).forEach((value, name) => {
    // 新建一行
    const row = document.createElement('tr');
    // 新建问题列、答案列
    const nameCell = document.createElement('td');
    const valueCell = document.createElement('td');
    // 赋值,用textContent避免XSS风险
    nameCell.textContent = name;
    valueCell.textContent = value;
    // 组装结构
    row.append(nameCell, valueCell);
    resultsTable.append(row);
});
</script>

如果确实需要直接插入HTML字符串,可以把append替换为insertAdjacentHTML,示例如下:

new URLSearchParams(window.location.search).forEach((value, name) => {
    resultsTable.insertAdjacentHTML('beforeend', `<tr><td>${name}</td><td>${value}</td></tr>`);
});

注意这种写法如果参数包含用户可控内容,存在XSS注入风险,生产环境建议优先使用手动创建元素的写法。


内容的提问来源于stack exchange,提问作者Geographos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 06:45:04