javascript - 无法从网站多次请求
问题描述
我正在尝试为一个学校项目制作一个 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`
})
});
});
解决方案
这是因为您创建了一个 XHR 对象。
每次向它发出请求时,都会取消之前的请求。
为每个请求创建一个新的 XHR 对象(在 getJSON 函数内)。
即交换顺序
let request = new XMLHttpRequest();
和
const getJSON = (link, action) => {
推荐阅读
- excel - 从多个excel文件复制单元格并将它们粘贴到主文件中
- sql - Oracle 数据库 - With 语句与 With 语句并在脚本中创建表
- perl - 在 perl 中计算 2 个点(2 组坐标)
- react-native - 不变违反 react-native-webview
- reactjs - 使用 React Hooks 从 firebase 读取数据到数组中
- javascript - 无法在 highchart 中显示列的数据标签,显示格式不正确
- reactjs - 在 React 的组件树中依赖 Context.Provider 的存在是否是一种反模式?
- c# - d:DataContext=d:DesignInstance 不起作用,甚至是普通的 UWP 项目
- google-bigquery - 使用浮动数据点计算大查询中的余数
- c# - SqlCommandBuilder 生成不正确的更新语句