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

如何在Jeopardy游戏的addGenre函数中使用API GET请求数据?

问题:Jeopardy游戏无法将API数据绑定到卡片

我正在开发一款Jeopardy游戏,需从API获取数据并展示在游戏卡片上。目前已通过API成功获取题目数据,但无法将数据应用到卡片中。我希望在addGenre()函数中访问getEasy函数内的res变量,为卡片分配题目内容。

现有代码

JavaScript

const game = document.querySelector("#game");
const scoreDisplay = document.getElementById("score");

// ("https://opentdb.com/api.php?amount=10&category=11&difficulty=easy&type=boolean");

const film = 11;
const levels = ["easy", "medium", "hard"];

function addGenre() {
  const column = document.createElement("div");
  column.classList.add("genre-column");
  column.innerText = "This is a genre";
  game.append(column);
  levels.forEach((lev) => {
    const card = document.createElement("div");
    card.classList.add("card");
    column.append(card);
    getEasy();
  });
}

const getEasy = async function (level) {
  const res = await axios.get(
    `https://opentdb.com/api.php?amount=10&category=11&difficulty=${level}`
  );
  console.log(res);
  return res;
};

addGenre();

CSS

body{
    margin: 0;
    padding: 0;
    background-color: dodgerblue;
    color: white;
    font-family: Arial, Helvetica, sans-serif;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
}

.genre-column{
    display: flex;
    flex-direction: column;
    text-align: center;

}

.card{
    width: 200px;
    height: 120px;
    border-radius: 20px;
    background-color: blue;
    text-align: center;
    padding: 5px;
    margin: 10px;
    border: 3px solid yellow;
}

HTML

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Jeopardy</title>
  <link href="https://fonts.googleapis.com/css?family=Copse&display=swap"
        rel="stylesheet">
  <link rel="stylesheet" href="app.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css">
</head>
<body>

<h1>Let's Play!</h1>
<div id="game">


</div>
<h2>Score : <span id="score">0</span></h2>

<script src="https://unpkg.com/jquery"></script>
<script src="https://unpkg.com/axios/dist/axios.js"></script>
<script src="https://unpkg.com/lodash"></script>
<script src="app.js"></script>

</body>
</html>

解决方案

问题核心在于异步函数的处理逻辑错误和参数缺失:

  1. getEasy是异步函数,直接调用只会返回Promise,必须用await或.then()获取实际返回数据
  2. 调用getEasy时未传入难度参数,导致API请求的difficulty字段无效

修改后的代码如下:

const game = document.querySelector("#game");
const scoreDisplay = document.getElementById("score");

const film = 11;
const levels = ["easy", "medium", "hard"];

// 转为异步函数以支持await操作
async function addGenre() {
  const column = document.createElement("div");
  column.classList.add("genre-column");
  column.innerText = "电影类";
  game.append(column);
  
  // 用for...of替代forEach,支持异步等待
  for (const lev of levels) {
    const card = document.createElement("div");
    card.classList.add("card");
    column.append(card);
    
    try {
      // 传入难度参数,等待API返回结果
      const res = await getEasy(lev);
      // 提取第一个题目内容(可根据需求调整)
      const question = res.data.results[0].question;
      // 将题目绑定到卡片
      card.innerText = question;
    } catch (err) {
      console.error("加载题目失败:", err);
      card.innerText = "加载失败";
    }
  }
}

const getEasy = async function (level) {
  const res = await axios.get(
    `https://opentdb.com/api.php?amount=10&category=${film}&difficulty=${level}`
  );
  return res;
};

addGenre();

关键修改说明:

  • 将addGenre改为异步函数,允许内部使用await等待API请求完成
  • 替换forEach为for...of循环,避免异步回调导致的执行顺序混乱
  • 调用getEasy时传入lev参数,确保API请求的难度参数正确
  • 通过res.data.results解析API返回的题目数据,将内容赋值给卡片
  • 添加try/catch捕获请求异常,处理加载失败场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 20:30:55