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

使用Fetch API获取数据时页面显示undefined的问题排查

问题分析与解决

核心问题:异步代码执行顺序错误

fetch是异步操作,它的.then()回调会在浏览器拿到API响应后才执行,但你的同步代码(document.getElementById("test").innerHTML = test)会在fetch还没返回数据时就先运行,此时test还是初始声明的undefined,所以页面显示undefined。

另外注意:从API返回的结构来看,res.data是一个数组,直接写res.data.policy会返回undefined,你需要遍历数组或者取数组中具体元素的policy字段。

修正后的代码

把更新DOM的操作放到fetch的.then()回调内部,确保只有拿到数据后再更新页面:

<div id="test"></div>
<script>
fetch("https://js.cexplorer.io/api-static/asset/list.json")
  .then((res) => res.json())
  .then((res) => {
    console.log(res);
    // 示例:把所有policy拼接成换行的字符串展示
    const policyList = res.data.map(item => item.policy).join('<br>');
    document.getElementById("test").innerHTML = policyList;
  })
  .catch(err => console.error('请求出错:', err)); // 增加错误捕获,方便排查问题
</script>

可选的async/await写法(更直观)

如果觉得链式.then()可读性差,可以用async/await语法改写:

<div id="test"></div>
<script>
async function loadAssetData() {
  try {
    const res = await fetch("https://js.cexplorer.io/api-static/asset/list.json");
    const data = await res.json();
    const policyList = data.data.map(item => item.policy).join('<br>');
    document.getElementById("test").innerHTML = policyList;
  } catch (err) {
    console.error('请求出错:', err);
  }
}
loadAssetData();
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 17:30:59