我试图使用fetch从JSON数组中输出球员的名字,并在我调用for的地方返回它,我可以将返回值插入到html元素中。
控制台记录了我想要的结果,但返回,在元素中返回undefined。
JSON API示例:
{
"PlayerID": 10000439,
"Jersey": 8,
"Position": "RF",
"FirstName": "Nick",
"LastName": "Castellanos"
}
HTML
<div id="scoreboard">
<div class="home">TEAM1<span class="runs"></span>0</div>
<div class="away">TEAM2<span class="runs"></span>0</div>
</div>
<div class="batting">
Batting:
<span id="batterPlayerName">
Player Name
</span>
</div>
<div class="pitching">
Pitching:
<span id="pitcherPlayerName">
Player Name
</span>
</div>
JS
function PlayerName(id) {
var url = `https://apiurl/Player/${id}`;
fetch(url)
.then(response => response.json())
.then(data => {
console.log(`${data.FirstName} ${data.LastName}`)
return data.FirstName + ' ' + data.LastName;
})
}
var curBatter = document.querySelector('#batterPlayerName');
var curPitcher = document.querySelector('#pitcherPlayerName');
curBatter.innerHTML = PlayerName('10000439');
curPitcher.innerHTML = PlayerName('10000526');
console:Nick Castellanos PlayerName div:击球:未定义
2条答案
按热度按时间gt0wga4j1#
您正试图在提取解析之前设置PlayerName的值。
如果你从PlayerName函数返回promise,那么一旦promise被解析,你就可以设置innerHtml。
或者,您可以 Package 整个函数以异步执行
d4so4syb2#
必须将HTML选择器声明为所属JSON