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

如何解决fetch API填充表格时重复创建tbody标签的问题?

解决方法

问题根源在于你直接把<td>标签插入到了<thead>后面,浏览器会自动补全表格的合法结构——<td>必须嵌套在<tr>里,而<tr>又必须放在<tbody>(或<thead>/<tfoot>)中,所以每次插入<td>时,浏览器都会自动生成一个新的<tbody>和<tr>来包裹这些单元格,最终导致多条数据对应多个<tbody>。

你可以按以下两种方式修改代码,把所有数据放到同一个<tbody>里:


方式一:拼接HTML字符串一次性插入(性能更优)

首先确保你的表格里已经有一个空的<tbody>标签,给它加个ID方便获取:

<table>
  <thead>
    <!-- 这里是你的表头内容 -->
  </thead>
  <tbody id="user-tbody"></tbody>
</table>

然后修改JavaScript代码,先把所有用户数据拼接成完整的<tr>字符串,再一次性插入到<tbody>中:

fetch(get_data)
.then(function (response) {
  return response.json(); // 直接用response.json()解析,替代text()+JSON.parse()
})
.then(function (obj) {
  let rowsHtml = '';
  obj.forEach(user => {
    // 每个用户对应一个<tr>,里面包含三个<td>
    rowsHtml += `
      <tr>
        <td class="customer" id="company${user.id}">${user.company}</td>
        <td class="customer" id="first_name${user.id}">${user.first_name}</td>
        <td class="customer" id="last_name${user.id}">${user.last_name}</td>
      </tr>
    `;
  });
  // 把拼接好的所有行插入到tbody中
  document.getElementById('user-tbody').innerHTML = rowsHtml;
})
.catch(function(error) {
  console.error('获取数据失败:', error);
});

方式二:动态创建DOM元素(更安全,避免XSS风险)

如果你的用户数据不可信(比如包含用户输入的内容),建议用DOM元素创建的方式,避免注入风险:

fetch(get_data)
.then(function (response) {
  return response.json();
})
.then(function (obj) {
  const tbody = document.getElementById('user-tbody');
  obj.forEach(user => {
    // 创建行元素
    const tr = document.createElement('tr');

    // 创建公司名称单元格
    const companyTd = document.createElement('td');
    companyTd.className = 'customer';
    companyTd.id = `company${user.id}`;
    companyTd.textContent = user.company;
    tr.appendChild(companyTd);

    // 创建名字单元格
    const firstNameTd = document.createElement('td');
    firstNameTd.className = 'customer';
    firstNameTd.id = `first_name${user.id}`;
    firstNameTd.textContent = user.first_name;
    tr.appendChild(firstNameTd);

    // 创建姓氏单元格
    const lastNameTd = document.createElement('td');
    lastNameTd.className = 'customer';
    lastNameTd.id = `last_name${user.id}`;
    lastNameTd.textContent = user.last_name;
    tr.appendChild(lastNameTd);

    // 把行添加到tbody
    tbody.appendChild(tr);
  });
})
.catch(function(error) {
  console.error('获取数据失败:', error);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 20:15:16