[英]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。 但是,它沒有顯示在表中。 我檢查了控制台日志,沒有錯誤。
由於data
是Object ,它沒有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.