javascript - 无法检索 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 不太熟悉,所以在这里我有点不适应。任何帮助表示赞赏。
解决方案
推荐阅读
- html - 如何以与带有图像的 div 相同的方式缩放 div 的高度?
- r - 如何在 org-mode 的 src 块之间传递一个或多个函数(不要使用 :session,使用 :var 或其他代替)
- python - 根据创建时间+日期重命名文件
- visual-studio-code - 如何在 VSCode 工作区中创建指向文件的链接
- asp.net-core - 在 ASP.NET Core 的约束中覆盖 RouteValueDictionary
- android - 如何在 android 中实现这种海浪进度(查看此 gif 图像)?
- python - 有没有办法找到每个组合以从每个列表中选择一个元素(在列表中)?
- python - 如何解决'列标签'Avg_Threat_Score'不是唯一的。'?熊猫的问题
- azure-ad-b2c - B2C OpenID 与 Azure AD 连接
- java - 如何将我的业务与 whatsup 业务 api 集成?