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

如何解决fetch生成HTML卡片时的'Uncaught (in promise) TypeError'错误

解决JSON数据读取与HTML卡片生成的错误问题

错误原因分析

  1. Promise链断裂:中间的then((json) => console.log(json))未返回JSON数据,导致后续then回调中的json为undefined,触发Cannot read properties of undefined (reading 'data')错误。
  2. JSON结构不匹配:你的JSON文件是直接的数组,而非包含data属性的对象,代码中json.data的写法不符合实际数据结构。
  3. DOM操作错误:
    • 错误使用document.innerHTML,应操作创建的wrapper元素内容;
    • 拼写错误:calss应为class;
    • 未将生成的卡片元素添加到页面DOM中。
  4. JSON语法错误:提供的示例JSON最后多了一个冗余的},会导致JSON解析失败。

修复步骤与完整代码

1. 修正JSON文件语法

删除最后一个对象后的多余},正确结构如下:

[
    {
      "Title": "3tene (PRO+Live2D DLC)",
      "Description": "Freemium",
      "Url": "https://3tene.com/series_purchase/",
      "Image": "https://images.unsplash.com/photo-1715329499545-f57d711c8209?q=80&w=1287&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
      "Tags": "Tracking"
    },
    {
      "Title": "Animaze",
      "Description": "Subscription",
      "Url": "https://store.steampowered.com/app/1364390/Animaze_by_FaceRig/",
      "Image": "https://images.unsplash.com/photo-1718002127392-92a7eef514ad?q=80&w=1287&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
      "Tags": "Tracking"
    }
]

2. 修正JavaScript代码

fetch('2D.json')
  .then(response => response.json())
  .then(json => {
    // 直接遍历JSON数组,无需.data
    json.forEach(ele => {
      const wrapper = document.createElement('div');
      // 给卡片添加类名方便样式控制
      wrapper.className = 'card';
      // 修正class拼写错误,正确设置内容
      wrapper.innerHTML = `
        <img src="${ele.Image}" alt="${ele.Title}">
        <h3 class="card-title">${ele.Title}</h3>
        <p class="card-description">${ele.Description}</p>
        <a href="${ele.Url}" target="_blank">查看详情</a>
      `;
      // 将卡片添加到页面body或指定容器
      document.body.appendChild(wrapper);
    });
  })
  .catch(error => console.error('加载或解析JSON失败:', error));

额外优化建议

  • 给卡片容器添加统一CSS样式,提升视觉效果;
  • 保留catch捕获请求或解析过程中的错误,便于调试;
  • 给图片添加alt属性,提升页面可访问性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 08:57:40