종우의 컴퓨터 공간

Data From an External API 본문

자바 스크립트 (JavaScript)/Asynchronous JS, Ajax & Fetch API

Data From an External API

종우공간 2021. 8. 10. 15:36
document.querySelector('.get-jokes').addEventListener('click', getJokes);

function getJokes(e) {
  const number = document.querySelector('input[type="number"]').value;

  const xhr = new XMLHttpRequest();

  // get it from the external API
  xhr.open('GET', `http://api.icndb.com/jokes/random/${number}`, true);

  xhr.onload = function() {
    if (this.status === 200) {
      const response = JSON.parse(this.responseText);
      
      let output = '';

      if (response.type === 'success') {
        response.value.forEach(function(joke) {
          output += `<li>${joke.joke}</li>`
        })
      } else {
        output += '<li>Something went wrong</li>';
      }

      document.querySelector('.jokes').innerHTML = output;
    }
  }

  xhr.send();

  e.preventDefault();
}

- external API를 사용하기 위해서는 해당하는 URI를 xhr.open()의 두번째 퍼레미터에 넣어주면 된다.