javascript 通过fetch函数返回json值

jhkqcmku  于 2023-09-29  发布在  Java
关注(0)|答案(2)|浏览(136)

我试图使用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:击球:未定义

gt0wga4j

gt0wga4j1#

您正试图在提取解析之前设置PlayerName的值。
如果你从PlayerName函数返回promise,那么一旦promise被解析,你就可以设置innerHtml。

function PlayerName(id) {
    var url = `https://apiurl/Player/${id}`;
    return fetch(url)
        .then(response => response.json())
        .then(data => {
            console.log(`${data.FirstName} ${data.LastName}`)
            return data.FirstName + ' ' + data.LastName;
        })
}

PlayerName('10000439').then(player => {
    var nameDiv = document.querySelector('#PlayerName')
    nameDiv.innerHTML = `Batting: ${player}`;
})

或者,您可以 Package 整个函数以异步执行

async function PlayerName(id) {
    var url = `https://apiurl/Player/${id}`;
    return 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');

(async () => {
    curBatter.innerHTML = await PlayerName('10000439');
    curPitcher.innerHTML = await PlayerName('10000526');
})();
d4so4syb

d4so4syb2#

必须将HTML选择器声明为所属JSON

相关问题