简体   繁体   English

如何使用上次调用的 API 填充 html 字段?

[英]How to fill html fields with last made API call?

I'm learning about rest APIs and async/await, so I'm just doing a tiny project with pokeapi.我正在学习 rest API 和 async/await,所以我只是在用 pokeapi 做一个小项目。

I got an event listener on "input" that calls the API and then fills in the html fields.我在“输入”上有一个事件侦听器,它调用 API,然后填充 html 字段。

The problem is, when an id is inserted eg "123" this will make three requests, fetchPokemon("1"), fetchPokemon("12") and fetchPokemon("123"), for now that is not a problem.问题是,当插入 id 时,例如“123”,这将发出三个请求,fetchPokemon("1")、fetchPokemon("12") 和 fetchPokemon("123"),目前这不是问题。 But what it sometimes does is that the second request "12" finishes after the third request "123" so the final filled in html field is with the data from "12" request.但有时它会在第三个请求“123”之后完成第二个请求“12”,因此最后填充的 html 字段是来自“12”请求的数据。

Is there an easy way around this to make it fill in always the last made request?有没有一种简单的方法可以使它始终填写最后提出的请求?

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 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>

The problem lies in the .addEventListener part.问题在于.addEventListener部分。

The input event is almost identical to the change event, which means everytime a user enters a key, it gets updated. input事件与change事件几乎相同,这意味着每次用户输入一个键时,它都会更新。 This is why it makes 3 calls with 1, 12 and 123这就是为什么它用1、12 和 123进行 3 次调用

Solution解决方案

Instead of input use submit on the form在表单上使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM