首页 > 解决方案 > 如何在 DOM 上显示嵌套数据?

问题描述

尝试从 API 获取数据并将其添加到 DOM

具体来说,一个包含对象的数组。

以下是 API 在控制台中返回的示例。

API 返回的 json

我正在使用 for 循环和 for...in 循环来访问对象中的数组

下面的代码

const getNews = document.getElementById('btn')

heyThere = () => {
    axios.get('https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=APIKEY')
        .then(function (response) {
            for (let i = 0; i <= response.data.articles.length; i++) {
                for (key in response.data.articles[i]) {
                    ham.innerHTML = (response.data.articles)
                }
            }
            console.log(response)
            console.log(typeof response)
        })
        .catch(function (error) {
            console.log(error);
        })
}

getNews.addEventListener('click', heyThere)

上面的代码将以下内容打印到 DOM

在此处输入图像描述

访问完整文章列表(20 篇文章)并将它们打印到 DOM 的正确方法是什么?

标签: javascriptarraysjsonfor-loopaxios

解决方案


您需要访问response.data.articles[i]要显示的特定属性,并为每个属性创建所需的 HTML。就像是:

const getNews = document.getElementById('btn')

heyThere = () => {
  axios.get('https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=APIKEY')
    .then(function(response) {
      let html = '';
      response.data.articles.each(article => {
        html += '<div class="article">';
        html += `<div class="author">${article.author}</div>`;
        html += `<div class="description">${article.description}</div>`;
        html += '</div>';
      });
      ham.innerHTML = html;
      console.log(response)
      console.log(typeof response)
    })
    .catch(function(error) {
      console.log(error);
    })
}

getNews.addEventListener('click', heyThere)


推荐阅读