【发布时间】:2021-01-26 17:44:14
【问题描述】:
我正在尝试为学校项目制作 pokedex,并且正在使用 JS 来做这件事。我发现了这个名为 pokeapi 的 api,由于它使用 JSON,我想只获取页面中的数据并返回它的 json,但是当我尝试使用我创建的方法在 for 循环中执行请求时,它似乎不起作用,只处理 for 循环的最后一个元素:
let request = new XMLHttpRequest();
const getJSON = (link, action) => {
request.open("GET", link);
request.send();
request.onload = () => {
if (request.status === 200) {
let json = JSON.parse(request.response);
action(json);
} else {
console.log(`e:${request.status} ${request.statusText}`);
}
}
}
let counter = 1;
getJSON("https://pokeapi.co/api/v2/pokedex/1/", (json) => {
json.pokemon_entries.forEach((poke_entry) => {
getJSON(poke_entry.pokemon_species.url, (poke_sp) => {
console.log(poke_sp);
//console loggin poke_sp only shows one console log, the last member of `json.pokemon_entries`
})
});
});
【问题讨论】:
标签: javascript json request xmlhttprequest