Skip to content

Instantly share code, notes, and snippets.

@jwo
Created June 14, 2017 16:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jwo/0de44f4709026aef3e3a36ff9ed28f57 to your computer and use it in GitHub Desktop.
Save jwo/0de44f4709026aef3e3a36ff9ed28f57 to your computer and use it in GitHub Desktop.
Fetch data from star wars api and display
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
.character {
display: flex;
width: 550px;
justify-content: space-between;
}
</style>
</head>
<body>
<div id="characters">
</div>
<script src="sw.js" charset="utf-8"></script>
</body>
</html>
function fetchPerson(id){
fetch(`http://swapi.co/api/people/${id}`)
.then( function(response){
return response.json()
})
.then(function(json){
console.log("data", json)
if (!json.name){
return;
}
const name = json.name;
const birth_year = json.birth_year;
/// If you were doing document.createElement
//const character = document.createElement('div');
//character.className = "character";
//character.textContent = name + ": " + birth_year;
//document.querySelector("#characters").appendChild(character)
const html = `
<div class="character">
<div class="name">
<a href="${json.url}">${name}</a>
</div>
<div class="year">${birth_year}</div>
</div>
document.querySelector("#characters").insertAdjacentHTML('afterbegin', html)
})
}
for (var i = 1; i <= 100; i++) {
fetchPerson(i)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment