javascript - 获取数据到表行和表列

标签 javascript html arrays

我正在尝试从 API 获取数据。

到目前为止,我已经尝试使用 API 获取数据。我一直在使用这个网站:https://www.geeksforgeeks.org/how-to-use-the-javascript-fetch-api-to-get-data/ 它当前 console.logs 我的数组,但它没有显示在我创建的表行中。 我想我可能在我的 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)

我的 javascript 看起来像这样:


// 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>

最佳答案

您需要正确处理响应。

工作示例:

// api url
const api_url = 'https://jsonplaceholder.typicode.com/comments';

// Defining async function
async function getapi(url) {
    await fetch(url)
        .then((response) => response.json())
        .then((data) => {
            console.log(data)
            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>id</th>
    <th>Name</th>
    <th>Body</th>
    <th>Email</th>
    </tr>`;
    
    // Loop to access all rows
    for (let r of data) {
        tab += `<tr>
            <td>${r.id}</td>
            <td>${r.name}</td>
            <td>${r.body}</td>
            <td>${r.email}</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>

关于javascript - 获取数据到表行和表列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74581857/

相关文章:

javascript - 我检测移动设备的方式有问题吗

javascript - DBSign 如何在仅浏览器解决方案中使用智能卡证书进行签名?

javascript - Android 等效于 HTML5 Canvas CompositeOperation

html - 大型 CSS 与大型 HTML

C - 在运行时 reshape 二维数组

javascript - NSData dataWithContentsOfUrl 需要 javascript

javascript - Angular 2 : what expressions can we interpolate in template

html - 如何在 <select> 元素旁边设置这个小按钮?

java - 使用 Arrays.toString 打印矩阵

python - Numpy:从数组中选择所有行和列