首页 > 解决方案 > 无法检索 Javascript 变量的 API 数据

问题描述

我正在使用 MLB API 来显示当天的比赛结果。当我进行 API 调用时,响应如下(出于发布目的而截断):

{
    "get": "games",
    "parameters": {
        "season": "2021",
        "date": "2021-04-29",
        "team": "26"
    },
    "results": 1,
    "response": [
        {
            "id": 62513,
            "date": "2021-04-29T17:10:00+00:00",
            "time": "17:10",
            "timestamp": 1619716200,
            "timezone": "UTC",
            "week": null,
            "teams": {
                "home": {
                    "id": 34,
                    "name": "Tampa Bay Rays",
                    "logo": "https://media.api-sports.io/baseball/teams/34.png"
                },
                "away": {
                    "id": 26,
                    "name": "Oakland Athletics",
                    "logo": "https://media.api-sports.io/baseball/teams/26.png"
                }
            },
            "scores": {
                "home": {
                    "hits": null,
                    "errors": null,
                    "innings": {
                        "1": null,
                        "2": null,
                        "3": null,
                        "4": null,
                        "5": null,
                        "6": null,
                        "7": null,
                        "8": null,
                        "9": null,
                        "extra": null
                    },
                    "total": null
                },
                "away": {
                    "hits": null,
                    "errors": null,
                    "innings": {
                        "1": null,
                        "2": null,
                        "3": null,
                        "4": null,
                        "5": null,
                        "6": null,
                        "7": null,
                        "8": null,
                        "9": null,
                        "extra": null
                    },
                    "total": null
                }
            }
        }
    ]
}

当我尝试以下操作时:

var awayTeam = response[0].teams.away.name;
document.getElementById('away-team').innerHTML = awayTeam;

var homeTeam = response[0].teams.home.name;
document.getElementById('home-team').innerHTML = homeTeam;

控制台显示此错误:

Uncaught TypeError: Cannot read property 'teams' of undefined

我究竟做错了什么?我对使用 API 不太熟悉,所以在这里我有点不适应。任何帮助表示赞赏。

标签: javascriptjsonapi

解决方案


推荐阅读