You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Ajax生成表格时表头重复显示的问题排查

问题解决:Ajax生成表格时重复显示表头

问题根源很清楚——你把表头的<tr><th>...</th></tr>代码写在了遍历用户数据的for循环内部,每处理一条用户数据就会重复输出一次表头,自然每条数据上方都出现了列名。

修复方案

把表头代码移到循环外部,只在表格最顶部生成一次;同时修正HTML结构,用<table>标签完整包裹表格内容(原代码缺少表格容器,可能引发渲染异常)。另外还修正了一处数据绑定错误:原代码中Email列错误绑定了username字段,现已改为正确的email。

修正后的完整代码

async function ajaxRequest() {
    const response = await fetch("https://jsonplaceholder.typicode.com/users");
    const obj = await response.json();
    displayInformation(obj);
}

function displayInformation(obj) {
    const divResponse = document.getElementById("divResponse");
    // 初始化表格容器与表头(循环外仅执行一次)
    let content = `
    <table>
        <tr>
            <th>User Name</th>
            <th>Username</th>
            <th>Email</th>
            <th>Phone</th>
        </tr>
    `;
    // 循环仅生成用户数据行
    for (const user of obj) {
        const tr = `
        <tr>
            <td>${user.name}</td>
            <td>${user.username}</td>
            <td>${user.email}</td>
            <td>${user.phone}</td>
        </tr>
        `;
        content += tr;
    }
    // 闭合表格标签
    content += "</table>";
    divResponse.innerHTML = content;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 23:50:26