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

JavaScript 解析JSON数据渲染到HTML表格的代码问题修复求助

问题根因
  • 重复执行JSON.parse解析同一段响应文本,多余且无意义。且误用了JSON.parse的第二个回调参数(reviver函数):该函数会遍历JSON所有层级的键值对依次触发,你写的判断value == "name"、value == "1day"的逻辑完全不符合提取字段的需求,只会导致渲染逻辑混乱。
  • 原有HTML结构只有固定的4个div容器,无法承载请求返回的多条产品数据,也无法实现你要的表格展示效果。
  • 字段提取逻辑错误:你请求返回的JSON是一个产品数组,每个数组元素是单个产品的完整数据,直接用data[key]取值的方式完全不匹配数组的结构。
修复后可运行代码

HTML 部分

<table border="1" cellpadding="8" cellspacing="0">
  <thead>
    <tr>
      <th>产品名称</th>
      <th>产品代码</th>
      <th>点差</th>
      <th>1日涨跌幅</th>
      <th>当前价格</th>
    </tr>
  </thead>
  <tbody id="productTableBody"></tbody>
</table>

JS 部分

function readTextFile(file, callback) {
  var rawFile = new XMLHttpRequest();
  rawFile.overrideMimeType("application/json");
  rawFile.open("GET", file, true);
  rawFile.onreadystatechange = function() {
    if (rawFile.readyState === 4 && rawFile.status == "200") {
      callback(rawFile.responseText);
    }
  }
  rawFile.send(null);
}

// 调用逻辑
readTextFile("https://assets.cmcmarkets.com/json/cmc-test-most-popular-feed.json", function(text) {
  // 只需要解析一次JSON即可
  const productList = JSON.parse(text);
  const tableBody = document.querySelector('#productTableBody');
  let htmlStr = '';
  // 遍历产品数组生成表格行
  productList.forEach(item => {
    htmlStr += `
      <tr>
        <td>${item.name}</td>
        <td>${item.code}</td>
        <td>${item.spread}</td>
        <td>${item['1day'].movement}</td>
        <td>${item['1day'].price}</td>
      </tr>
    `;
  });
  tableBody.innerHTML = htmlStr;
});
修复说明
  1. 把HTML替换为标准的表格结构,用tbody承载动态生成的产品数据行
  2. 删除了重复的JSON.parse调用和错误的reviver回调逻辑,仅做一次JSON解析即可拿到完整的产品数组
  3. 遍历产品数组,逐个提取每个产品的对应字段拼接成表格行HTML,一次性插入到页面中,渲染效率更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 06:15:03