Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

99
Visualizações
Api call doesn't jQuery / javascript

I am trying use the pokeApi for a site but my function doesn't work the second time.

The result in next = the next link I want to use that the Api returns.

const beginLink = "https://pokeapi.co/api/v2/pokemon/";
let next;
let previous;
apiCall(beginLink);

function apiCall(link) {
  $('#pokemons').html(``);
  $.ajax({
    url: link
  }).done(handleResponse);
  
  function handleResponse(data) {
    next = data.next;
    previous = data.previous;
    for (let i = 0; i < 20; i++) {
      $('#pokemons').append(`<div class="pokemon"><img src="https://raw.githubusercontent.com/msikma/pokesprite/master/pokemon-gen8/regular/${data.results[i].name}.png"><br><p>${data.results[i].name}</p></div>`);
    }
  }
}

$("#next").on("click ", apiCall(next));
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The main issue is because apiCall(next) doesn't return a function. Therefore, when the click event occurs nothing happens.

To fix this issue, and also to remove the reliance on global variables which should avoided, you can place the URL of the next call in to the data held by the #next element. This way the function which updates the content of the DOM based on the AJAX response is entirely self-contained.

let $next = $('#next');
let $pokemonContainer = $('#pokemons');

function apiCall() {
  $pokemonContainer.empty();
  $.get($next.data('url')).done(handlePokemonApiResponse);
}

function handlePokemonApiResponse(data) {
  $next.data('url', data.next);
  let html = data.results.map(p => `<div class="pokemon"><img src="https://raw.githubusercontent.com/msikma/pokesprite/master/pokemon-gen8/regular/${p.name}.png"><br><p>${p.name}</p></div>`);
  $pokemonContainer.html(html);
}

$next.on("click", apiCall).trigger('click');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button type="button" id="next" data-url="https://pokeapi.co/api/v2/pokemon/">Next</button>
<div id="pokemons"></div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda