首页 > 解决方案 > 无法从网站多次请求

问题描述

我正在尝试为一个学校项目制作一个 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`
    })
  });
});

标签: javascriptjsonrequestxmlhttprequest

解决方案


这是因为您创建了一个 XHR 对象。

每次向它发出请求时,都会取消之前的请求。

为每个请求创建一个新的 XHR 对象(在 getJSON 函数内)。

即交换顺序

let request = new XMLHttpRequest();

const getJSON = (link, action) => {

推荐阅读