조크 생성기 API

jb kim·2021년 8월 26일
0

Ajax Fetch API

목록 보기
5/8

조크 API

랜덤 조크

http://api.icndb.com/jokes/random

결과

{
"type": "success",
"value": {
"id": 607,
"joke": "Chuck Norris plays pool with comets and astroids. He shoots them into black holes.",
"categories": []
}
}

index.html

<!DOCTYPE html>
<html lang="ko">

<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css" />
  <title>Joke Generator</title>
</head>

<body>
  <div class="container">
    <h2>조크 생성기</h2>
    <form>
      <div>
        <label for="number">Number of jokes</label>
        <input type="number" id="number">
      </div>
      <div>
        <button class="get-jokes">Get Jokes</button>
      </div>
    </form>
    <ul class="jokes"></ul>
  </div>

  <script src="app.js"></script>
</body>

</html>

app.js

document.querySelector('.get-jokes').addEventListener('click', getJokes);

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

	//xhr 객체 생성후 조크 api 주소를 이용해 조크 불러오기

  e.preventDefault();
}

객체 생성

const xhr = new XMLHttpRequest();

open 메소드

xhr.open('GET', http://api.icndb.com/jokes/random/${number}, true);

send 메소드

xhr.send();

send 메소드 위에 onload 메소드 작성하기

xhr.onload = function() {
if(this.status === 200) {
console.log(this.responseText);
//const response = JSON.parse(this.responseText);
}
}

onload 메소드

  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;
    }
  }
profile
픽서

0개의 댓글