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

JavaScript异步请求报错:Uncaught (in promise) ReferenceError求助

问题分析与修复方案

核心错误点

  1. 变量作用域问题:tab定义在内部函数show中,外部return tab时无法访问,直接触发ReferenceError。
  2. API数据结构误解:https://api.chucknorris.io/jokes/random返回的是单个笑话对象,不存在list属性,循环data.list会导致额外错误。
  3. DOM操作错误:<h1>元素没有value属性,需用innerHTML设置内容。
  4. 函数未执行:定义了show函数但从未调用,核心逻辑完全没触发。

修正后的完整代码

JavaScript

async function fetchRandomJokes() {
  try {
    const response = await fetch("https://api.chucknorris.io/jokes/random");
    const data = await response.json();

    // 直接处理单个笑话数据,无需循环
    let tab = `
      <tr>
        <th>url</th>
        <th>value</th>
      </tr>
      <tr>
        <td>${data.url}</td>
        <td>${data.value}</td>
      </tr>
    `;
    // 用innerHTML设置内容,包裹成表格结构
    document.getElementById("quotes").innerHTML = `<table>${tab}</table>`;
    return tab;
  } catch (error) {
    console.error("获取笑话失败:", error);
    document.getElementById("quotes").textContent = "加载失败,请重试";
  }
}

CSS

#button1 {
  border: 2px solid #000; /* 补充边框样式,原代码仅设置宽度无样式 */
  background-color: #007bff; /* 添加背景色让按钮可见 */
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px 2px;
  cursor: pointer;
}

table {
  border-collapse: collapse;
  margin-top: 20px;
}

th, td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

HTML

<!DOCTYPE html>
<html>
<head>
  <style>
    /* 可将CSS内联或单独引入 */
    #button1 {
      border: 2px solid #000;
      background-color: #007bff;
      color: white;
      padding: 15px 32px;
      text-align: center;
      text-decoration: none;
      display: inline-block;
      font-size: 16px;
      margin: 4px 2px;
      cursor: pointer;
    }

    table {
      border-collapse: collapse;
      margin-top: 20px;
    }

    th, td {
      border: 1px solid #ddd;
      padding: 8px;
      text-align: left;
    }
  </style>
</head>
<body>
  <button id="button1" onClick="fetchRandomJokes()">Quotes</button>
  <div id="quotes"></div> <!-- 用div代替h1更适合放置表格 -->
</body>
</html>

额外优化说明

  • 增加try/catch捕获请求异常,避免控制台出现未捕获的Promise错误。
  • 补充按钮样式,解决原按钮因无背景色和边框样式可能不可见的问题。
  • 替换<h1>为<div>,符合语义化规范,h1应为标题而非容器。
  • 简化逻辑,适配API返回的单个数据结构,无需循环。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 05:53:18