【发布时间】:2020-04-05 17:31:01
【问题描述】:
我想在 HTML 表格中显示 ajax URL 数据显示,但我不知道为什么它显示为 undefined 帮帮我,我找不到错误
$.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>
但它显示我未定义
【问题讨论】:
-
为什么每次迭代都要重写表中的所有内容?它给你 undefined 因为请求返回一个对象,你试图访问一个不存在的属性。
-
如何添加该对象@RaulSauco
标签: javascript arrays json ajax