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

如何将Football API返回的数组数据从控制台展示到页面div中

实现步骤

1. 修改HTML,添加赛事展示容器

在页面中新增一个用于承载赛事数据的div,给它设置唯一ID方便后续操作:

<html lang="en">
<head>
</head>
<body>
  <div class="page-header">
    <h1>Football API</h1>
  </div>
    <button type="button" onClick="getgames()">Check info</button>
    <!-- 新增的展示容器 -->
    <div id="game-container"></div>
<script src="js/main.js"></script>
</body>
</html>

2. 修正JavaScript代码,完成数据渲染

先纠正你初步思路里的拼写错误(lenght改为length),然后正确访问赛事对象的具体字段,最后把拼接好的HTML插入到容器中:

async function getgames(){
    const settings = {
        "async": true,
        "crossDomain": true,
        "url": "https://football-prediction-api.p.rapidapi.com/api/v2/predictions?market=classic&iso_date=2018-12-01&federation=UEFA",
        "method": "GET",
        "headers": {
            "X-RapidAPI-Key": "$APIKEY",
            "X-RapidAPI-Host": "football-prediction-api.p.rapidapi.com"
        }
    };

    $.ajax(settings).done(function (response) {
        // 从响应中取出赛事数组(根据控制台打印的实际结构调整,这里假设是predictions字段)
        const games = response.predictions;
        let text = "<ul>";
        // 遍历每条赛事数据
        for (let i = 0; i < games.length; i++) {
            const game = games[i];
            // 拼接具体字段内容,字段名请对照控制台打印的response结构修改
            text += `
                <li style="margin: 10px 0; padding: 10px; border: 1px solid #eee;">
                    <strong>比赛日期:</strong> ${game.iso_date}<br>
                    <strong>对阵:</strong> ${game.home_team} VS ${game.away_team}<br>
                    <strong>预测结果:</strong> ${game.prediction}<br>
                    <strong>联赛:</strong> ${game.league}
                </li>
            `;
        }
        text += "</ul>";
        // 将拼接好的HTML插入到容器中
        $("#game-container").html(text);
    });
}

关键注意点

  • 字段匹配:代码里的iso_date、home_team等字段是根据该API文档推测的,你需要对照控制台打印的response结构,替换成实际存在的字段名。
  • 拼写修正:原思路里的games.lenght是拼写错误,必须改为games.length,否则循环无法正常执行。
  • 样式优化:给li标签加了简单样式,你可以根据需求调整或移除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 23:30:57