我正在尝试使用JavaScript构建API,以便从该URL提取json数据的数据:img,a,c。但是下面的代码抛出了错误
application.js:10未捕获(承诺)TypeError:
data.forEach
不是函数
(为什么未定义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);
});
});
{
"a": "shoujo-apocalypse-adventure",
"c": [
"Adventure",
"Drama",
"Psychological",
"Sci-fi",
"Seinen",
"Slice of Life",
"Tragedy"
],
"h": 156,
"i": "5c410d31719a16035a4647cc",
"im": "4a/4a1f2a595e0e84e62f6ceddf3946274478928ca99e8df86bc6511b6e.png",
"ld": 1547822837.0,
"s": 2,
"t": "Shoujo Apocalypse Adventure"
},
答案 0 :(得分:0)
响应不是数组([]
),而是对象({}
),对象没有方法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);
});
});
<ul id="results"></ul>
https://jsbin.com/gecusi/edit?html,js
注意:在示例中,我slice
数组是因为有大约6.7k电影,并且我不想阻止浏览器。