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

使用JavaScript Fetch获取API用户数据后无法更新DOM显示的问题

解决Fetch获取API数据并展示到HTML的问题

问题概述

尝试通过Fetch从API获取用户数据并展示到HTML页面,初始代码可在控制台看到数据,但添加循环插入逻辑后页面无内容,控制台无报错。

核心错误点

  • 接口路径错误:https://dummyjson.com/user返回单个用户对象,而非用户数组,无法用forEach遍历;需改用https://dummyjson.com/users获取用户列表。
  • Promise链数据丢失:then(data => console.log(data))未返回数据,导致后续then中的data为undefined,遍历操作无法执行。
  • DOM选择器错误:document.querySelector('item')会查找<item>标签,实际应选择id为item的div,需改为document.querySelector('#item')。

修正后的完整代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <style>
        body {
      background: transparent;
      color: #2c0493;
      padding: 44px;
      margin: 0;
      height: 100vh;
      align-items: center;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
        Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
    }

    h3,
    h2 {
      margin: 0;
    }
  </style>
</head>
<body>
  <h2 id="header">GET Data from API</h2>
  <h3>And display in HTML with JavaScript</h3>
  <hr />
  <div id="item"></div>
  <script>
    fetch('https://dummyjson.com/users')
      .then(result => result.json())
      .then(data => {
        console.log(data);
        // 获取目标容器
        const container = document.querySelector('#item');
        // 遍历用户列表(注意dummyjson返回的用户数组嵌套在data.users下)
        data.users.forEach(user => {
          const userHtml = `<p>${user.firstName}</p>`;
          container.insertAdjacentHTML('afterbegin', userHtml);
        });
      })
      .catch(error => console.error('请求出错:', error)); // 添加错误捕获便于调试
  </script>
</body>
</html>

额外优化说明

  • 添加catch块捕获请求或数据处理过程中的错误,便于排查问题。
  • 提前获取DOM容器,避免每次循环重复查询DOM,提升性能。
  • 适配dummyjson.com/users的数据结构,用户数组实际嵌套在返回对象的users属性中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 14:47:42