如何用JavaScript获取API来显示数据?

hjzp0vay  于 2023-11-15  发布在  Java
关注(0)|答案(1)|浏览(127)

我试图用JavaScript构建一个API来从JSON数据的URL中获取数据:img,a,c,但下面的代码返回了一个错误:
application.js:10 Uncaught(in promise)TypeError:data.forEach is not a function
(why forEach方法没有定义)你能帮忙吗?

var results = document.getElementById("results");

fetch("https://www.mangaeden.com/api/list/0/")
  .then(response => response.json())
  .then((data) => {

    data.forEach((result) => {

      const movies = '<li><img src="' + result.im + '" alt=""><h3>' + result.a + '</h3><p>' + result.c + '</p></li>';
      results.insertAdjacentHTML("beforeend", movies);

    });
  });

个字符

nwlls2ji

nwlls2ji1#

响应不是一个数组([]),而是一个对象({}),对象没有方法forEach。我猜你是想在条目上运行forEach,在本例中是在data.manga下。

var results = document.getElementById("results");

fetch("https://www.mangaeden.com/api/list/0/", {
    mode: 'cors'
  })
  .then(response => response.json())
  .then((data) => {

    data.manga
      .filter(movie => movie.c.includes('Action') || movie.c.includes('Adventure'))
      .slice(0, 10).forEach((result) => {

      const movies = '<li><img src="https://cdn.mangaeden.com/mangasimg/' + result.im + '" alt=""><h3>' + result.a + '</h3><p>' + result.c + '</p></li>';
      results.insertAdjacentHTML("beforeend", movies);

    });
  });

个字符
https://jsbin.com/gecusi/edit?html,js

注意:在示例中,我slice数组,因为有~6.7k的电影,我不想阻止浏览器。

相关问题