gpt4 book ai didi

javascript - json数据显示在表格中

转载 作者:行者123 更新时间:2023-12-02 21:12:40 24 4
gpt4 key购买 nike

我想将 ajax URL 数据显示到 HTML 表中,但我不知道为什么它显示未定义 帮助我,我找不到错误

$.ajax({
url: 'https://api.thevirustracker.com/free-api?countryTotals=ALL',
dataType: 'json',
success: function(data) {
for (let i = 0, n = data.countryitems.length; i < n; i++) {
const entries = data.countryitems[i]
Object.keys(entries).forEach(key => {
console.log(key, entries[key])
document.getElementById('table').innerHTML =
`<table class="table table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Country Name</th>
<th scope="col">Infected</th>
<th scope="col">Recovered</th>
<th scope="col">Unresolved</th>
<th scope="col">Deaths</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">${key,entries[key].ourid}</th>
<td>${key,entries[key].title}</td>
<td>${key,entries[key].total_cases}</td>
<td>${key,entries[key].total_recovered}</td>
<td>${key,entries[key].total_unresolved}</td>
<td>${key,entries[key].total_deaths}</td>
</tr>
</tbody>
</table>`
});
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="col" id="table"></div>
</div>

但它显示我未定义

最佳答案

所有国家/地区数据都位于一个对象中,该对象是数组的第一个元素,按如下方式访问它:

const entries = data.countryitems[0];

$.ajax({
url: 'https://api.thevirustracker.com/free-api?countryTotals=ALL',
dataType: 'json',
success: function(data) {

// Access the data with [0]
const entries = data.countryitems[0];

// Create an element to store the content you will create
let html = '';

Object.keys(entries).forEach(key => {

// The last object on entries is 'stat': 'ok' don't add it
if (key !== 'stat') {

// Add content to the element, not to the DOM
html +=
`<tr>
<th scope="row">${key,entries[key].ourid}</th>
<td>${key,entries[key].title}</td>
<td>${key,entries[key].total_cases}</td>
<td>${key,entries[key].total_recovered}</td>
<td>${key,entries[key].total_unresolved}</td>
<td>${key,entries[key].total_deaths}</td>
</tr>`;

}
});

// Add all the content to the DOM at once, only one redraw
document.getElementById('t-body').innerHTML = html;

}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Country Name</th>
<th scope="col">Infected</th>
<th scope="col">Recovered</th>
<th scope="col">Unresolved</th>
<th scope="col">Deaths</th>
</tr>
</thead>
<tbody id="t-body"></tbody>
</table>

关于javascript - json数据显示在表格中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61046657/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com