Skip to content

Instantly share code, notes, and snippets.

@thuyanduong
Last active February 17, 2021 20:53
Show Gist options
  • Save thuyanduong/f86457477d9816860955c46c6e5b5602 to your computer and use it in GitHub Desktop.
Save thuyanduong/f86457477d9816860955c46c6e5b5602 to your computer and use it in GitHub Desktop.
Build your first AJAX Webpage

Create Studio Ghibli Webpage!

You are allowed to copy and paste the code below from today's lecture. You should use it to create a similar web page with the following user story:

As a user, when I click on the button, I should see a list of Studio Ghibli characters.

You should use the Stuido Ghibli API:

When you are finished, experiment with other APIs.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>APIs and AJAX</title>
  </head>
  <body>
    <button>Show Characters</button>
    <div>
      <ul id="container">
      </ul>
    </div>
    <script src="index.js"></script> 
  </body>
</html>
// 1st step is when the button is clicked 
document.querySelector("button").addEventListener("click", makeRequest)

//2nd step is make a request to the API URL: https://rickandmortyapi.com/api/character
function makeRequest(){
  let request = new XMLHttpRequest()
  request.open('GET', 'https://rickandmortyapi.com/api/character')
  request.send()
  request.addEventListener("readystatechange", showCharacters)
  //request.onload = callback()
}

//3rd take the data and put it in the DOM
function showCharacters(e){
  let request = e.target;
  if(request.readyState === 4){
    let object = JSON.parse(request.response)
    object.results.forEach(person => {
      let li = document.createElement("li")
      li.innerText = person.name
      document.querySelector("ul").append(li)
    })
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment