我正在try 从API获取数据.
到目前为止,我已经try 使用API获取数据.我一直在使用这个网站:https://www.geeksforgeeks.org/how-to-use-the-javascript-fetch-api-to-get-data/ 它当前对我的数组进行sole.log,但它不会显示在我创建的表行中. 我想我可能在我的html中创建了错误的行,但我不知道应该如何设置它们.请展示一个小例子或谷歌,如果这是什么是错误的.
The current error message i get is
Uncaught (in promise) TypeError: data.list is not iterable
at show (news.js:37:21)
at getapi (news.js:17:2)
我的脚本如下所示:
// api url
const api_url =
"https:newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=xxxxxxxxx";
// Defining async function
async function getapi(url) {
// Storing response
const response = await fetch(url);
// Storing data in form of JSON
var data = await response.json();
console.log(data);
if (response) {
hideloader();
}
show(data);
}
// Calling that async function
getapi(api_url);
// Function to hide the loader
function hideloader() {
document.getElementById('loading').style.display = 'none';
}
// Function to define innerHTML for HTML table
function show(data) {
let tab =
`<tr>
<th>Author</th>
<th>Title</th>
<th>Description</th>
<th>Url</th>
</tr>`;
// Loop to access all rows
for (let r of data.list) {
tab += `<tr>
<td>${r.author}</td>
<td>${r.title}</td>
<td>${r.description}</td>
<td>${r.url}</td>
</tr>`;
}
// Setting innerHTML as tab variable
document.getElementById("news").innerHTML = tab;
}
<!DOCTYPE html>
<html lang="en">
<head>
<script src="news.js"></script>
<link rel="stylesheet" href="test.css" />
<meta charset="UTF-8" />
<meta name="viewport"
content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<!-- Here a loader is created which
loads till response comes -->
<div class="d-flex justify-content-center">
<div class="spinner-border"
role="status" id="loading">
<span class="sr-only">Loading...</span>
</div>
</div>
<h1>News</h1>
<!-- table for showing data -->
<table id="news"></table>
</body>
</html>