[英]How to fill html fields with last made API call?
我正在学习 rest API 和 async/await,所以我只是在用 pokeapi 做一个小项目。
我在“输入”上有一个事件侦听器,它调用 API,然后填充 html 字段。
问题是,当插入 id 时,例如“123”,这将发出三个请求,fetchPokemon("1")、fetchPokemon("12") 和 fetchPokemon("123"),目前这不是问题。 但有时它会在第三个请求“123”之后完成第二个请求“12”,因此最后填充的 html 字段是来自“12”请求的数据。
有没有一种简单的方法可以使它始终填写最后提出的请求?
const pokemonId = document.getElementById("pokemon-id");
const pokemonName = document.getElementById("pokemon-name");
const pokemonType = document.getElementById("pokemon-type");
const pokemonHeight = document.getElementById("height");
const pokemonWeight = document.getElementById("weight");
const pokemonSearch = document.getElementById("pokemon-search");
async function fetchPokemon(idOrName) {
const endpoint = "https://pokeapi.co/api/v2/pokemon/";
const response = await fetch(endpoint + idOrName);
if (!response.ok) return null;
return response.json();
}
function fillPokemonFields(pokemon) {
if(!pokemon) return;
pokemonId.textContent = pokemon.id;
pokemonName.textContent = pokemon.name;
pokemonType.textContent = pokemon.type;
pokemonHeight.textContent = pokemon.height;
pokemonWeight.textContent = pokemon.weight;
}
pokemonSearch.addEventListener("input", async function () {
let input = this.value;
let pokemon;
// TODO validation
pokemon = await fetchPokemon(input);
fillPokemonFields(pokemon);
});
html
<main>
<input type="text" id="pokemon-search">
<div id="pokemon-id"></div>
<div id="pokemon-name"></div>
<div id="pokemon-type"></div>
<div id="pokemon-height"></div>
<div id="pokemon-weight"></div>
</main>
.addEventListener
部分。 input
事件与change
事件几乎相同,这意味着每次用户输入一个键时,它都会更新。 这就是为什么它用1、12 和 123进行 3 次调用
在表单上使用submit
而不是input
yourFormElement.addEventListener("submit", function (e) {
// this is needed to avoid default functionality of the onsubmit method
e.preventDefault();
// do stuff here...
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.