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

求助:调用API后HTML页面出现‘undefined’文本的原因排查及解决方案建议

为什么页面会出现‘undefined’?

嘿,我一眼就揪出问题啦!你代码里的output变量只做了声明但没初始化,它的默认值是undefined——当你第一次执行output += ...的时候,就相当于把undefined和后面的HTML字符串硬拼在了一起,这就是页面上莫名出现‘undefined’的根源!

修复方法

只需要把let output;改成let output = '';(初始化为空字符串)就行啦,修改后的完整代码如下:

// Load list of blog posts
window.onload = function() {
 fetch('https://jsonplaceholder.typicode.com/posts?userId=1')
 .then((response) => response.json())
 .then((posts) => {
 let output = ''; // 这里初始化空字符串,避免拼接undefined
 posts.forEach(function(post) {
 output += `
 <li class="post">
 <h2><a href="#" target="_blank">${post.title}</a></h2>
 <p>${post.body}</p>
 </li>
 `
 });
 document.querySelector('#posts').innerHTML = output;
 });
};

给API新手的小建议

  • 别忘了处理请求错误:fetch只会在网络彻底失败时触发reject,所以最好手动检查响应状态,避免拿到无效数据:
    .then((response) => {
      if (!response.ok) {
        throw new Error(`请求失败!状态码: ${response.status}`);
      }
      return response.json();
    })
    .catch(error => console.error('获取数据出错:', error));
    
  • 更简洁的字符串生成方式:可以用map方法生成HTML片段数组,再用join拼接,比forEach手动累加更清爽:
    const output = posts.map(post => `
      <li class="post">
        <h2><a href="#" target="_blank">${post.title}</a></h2>
        <p>${post.body}</p>
      </li>
    `).join('');
    
  • 变量初始化要成习惯:声明变量时尽量给个初始值,能避免很多像这样的隐性bug~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 17:12:40