因此,我在index.html中绑定了一个脚本,该脚本实际上必须从api中获取json数组,然后在获得响应时动态更新页面。
但是,结果是我得到了我页面的唯一更新。
这是我的脚本
fetch(url)
.then((resp) => resp.json())
.then((resp) => {
resp.results.forEach(item => {
fetch(item.url)
.then((response)=> response.json())
.then((response) => pokeArr.push(response))
.catch(console.log)
})
}).catch(console.log)
const filler = () => {
if(!pokeArr) return 0
pokeArr.map((i,j)=>{
return `<tr>${i.name}</tr>`
})
}
const pokeindex = () => {
document.getElementById('a').appendChild(document.createElement(filler()))
}
pokeindex()
当我安慰它时,我可以在控制台中看到我收到的所有响应,因此至少我正在正确地进行获取。
答案 0 :(得分:0)
这里有很多问题:
您在一个地方有parberakan
,但在另一个地方pokeArr
;在一条评论中,您建议它们是同一件事。
您不要在引用的代码中的任何地方声明parberakan
/ pokeArr
。
引用的代码中没有任何内容正在等待各种fetch
调用完成(甚至没有第一个调用,尤其是没有在其then
处理程序之一中进行的一系列调用)。
fetch
呼叫未检查.ok
;参见the post on my anemic little blog。
document.createElement
不接受HTML字符串。它接受要创建的单个元素的标签名称(例如document.createElement("div")
)。
filler
不返回map
的结果。
将console.log
直接传递到catch
并不是100%可靠。
粗略的猜测,我怀疑您想做这样的事情(请参阅评论),但是我建议您从当前任务中退一步,并逐步完成一些基本教程:
// Create these functions first
const filler = (pokeArray) => { // Accept the array as a parameter
if(!pokeArray) return null; // Recommend null instead of 0 if the other return is an array
return pokeArray.map((i,j)=>{ // Return the result of `map`
return `<tr>${i.name}</tr>`;
});
};
const pokeindex = (pokeArray) => { // Accept the array as a parameter
// I'm assuming the element with id="a" is a `table` or `tbody`
document.getElementById('a').insertAdjacentHTML( // This accepts HTML
"beforeend",
fillter(pokeArray)
);
}
fetch(url)
.then((resp) => {
// Check .ok
if (!resp.ok) {
throw new Error("HTTP error " + resp.status);
}
return resp;
})
.then((resp) => resp.json())
.then((resp) => Promise.all(resp.results.map(item => { // Wait for all these to complete;
// result is an array of the
// resolution values
return fetch(item.url)
.then((response) => {
// Check .ok
if (!response.ok) {
throw new Error("HTTP error " + resp.status);
}
return response;
})
.then((response) => response.json());
})))
.then((pokeArray) => {
// Now we have the array and can do something
pokeindex(pokeArray);
})
.catch(error => { console.log(error); }); // Passing `console.log` directly isn't reliable
不过,我可能没有抓住所有最后的小事情。这只是为了帮助您指出正确的方法。