簡體   English   中英

如何使用Fetch API顯示HTML表中的數據

[英]How to display data in an HTML table using Fetch API

我正在嘗試將從 API 獲取的數據顯示到 HTML 表中。 我的代碼如下:

 <div class="container2">
  <table class="table">
    <thead>
      <tr>
        <th>TEAM</th>
        <th>GP</th>
        <th>WON</th>
        <th>DRAW</th>
        <th>LOST</th>
        <th>POINTS</th>
        <th>SCORED</th>
        <th>CONCEDED</th>
      </tr>
    </thead>
    <tbody id="data">
    </tbody>
  </table>
</div>
fetch("https://heisenbug-premier-league-live-scores-v1.p.rapidapi.com/api/premierleague/table", {
    "method": "GET",
    "headers": {
        "x-rapidapi-host": "host",
        "x-rapidapi-key": "key",
    }
}).then(
  response => {
    response.json().then(
      data =>{
       
        console.log(data);
        if (data.length > 0){
          var temp = "";
          
          data.forEach((x) => {
            temp += "<tr>";
            temp += "<td>"+ x.team +"</td>";
            temp += "<td>"+ x.played +"</td>";
            temp += "<td>"+ x.win +"</td>";
            temp += "<td>"+ x.draw +"</td>";
            temp += "<td>"+ x.loss +"</td>";
            temp += "<td>"+ x.goalsFor +"</td>";
            temp += "<td>"+ x.goalsAgainst +"</td>";
            temp += "<td>"+ x.points +"</td>";
            temp += "</tr>"
          });
          
          document.getElementById("data").innerHTML = temp;
        }
      }
    )
})

運行時,將獲取 API 並成功檢索到 object。 但是,它沒有顯示在表中。 我檢查了控制台日志,沒有錯誤。

由於dataObject ,它沒有length屬性,因此條件變為false

但是,所需數據應該在data.records中。 只需將if條件更改為data.records.length > 0而不是迭代data ,而是在data.records上這樣做可以解決問題。

 fetch("https://heisenbug-premier-league-live-scores-v1.p.rapidapi.com/api/premierleague/table", { "method": "GET", "headers": { "x-rapidapi-host": "host", "x-rapidapi-key": "key", } }).then( response => { response.json().then( data => { console.log(data); var temp = ""; data.records.forEach((x) => { temp += "<tr>"; temp += "<td>" + x.team + "</td>"; temp += "<td>" + x.played + "</td>"; temp += "<td>" + x.win + "</td>"; temp += "<td>" + x.draw + "</td>"; temp += "<td>" + x.loss + "</td>"; temp += "<td>" + x.goalsFor + "</td>"; temp += "<td>" + x.goalsAgainst + "</td>"; temp += "<td>" + x.points + "</td>"; temp += "</tr>" }); document.getElementById("data").innerHTML += temp; } ) })
 <div class="container2"> <table class="table" border="1"> <thead> <tr> <th>TEAM</th> <th>GP</th> <th>WON</th> <th>DRAW</th> <th>LOST</th> <th>POINTS</th> <th>SCORED</th> <th>CONCEDED</th> </tr> </thead> <tbody id="data"></tbody> </table> </div>

編輯:正如@Phil 所指出的,數據檢查是多余的,因此將其從代碼片段中刪除。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM