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

使用fetch获取API数据可在console.log输出但无法渲染到div如何解决

问题原因
  • 现有代码的fetch异步回调中仅执行了控制台打印逻辑,没有写入DOM的相关操作
  • 单独书写的document.getElementById("console")仅完成了DOM节点获取,没有执行内容赋值,且该语句位于fetch逻辑之外,无法拿到异步返回的接口数据
修正代码

JavaScript 代码

// 提前获取目标DOM节点
const consoleDiv = document.getElementById("console")

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => {
    // 保留控制台打印逻辑
    console.log(json)
    // 将数据格式化后写入页面div,使用textContent可避免XSS风险
    consoleDiv.textContent = JSON.stringify(json, null, 2)
    // 若只需展示单个字段,可直接读取对应属性,例如:consoleDiv.textContent = json.title
  })

HTML 代码(无需修改)

<div id="console"></div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 01:06:04