【问题标题】:Can't request from website multiple times无法从网站多次请求
【发布时间】: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


    【解决方案1】:

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

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

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

    即交换顺序

    let request = new XMLHttpRequest();
    

    const getJSON = (link, action) => {
    

    【讨论】:

    • 在某些浏览器中执行多个请求时很脆弱,并且它无法同时执行多个请求
    猜你喜欢
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多