Created
February 14, 2017 12:53
-
-
Save dagolinuxoid/183d1fd9784300fb24ce3a80559dc356 to your computer and use it in GitHub Desktop.
#json #ajax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var pageCounter = 1; | |
var animalContainer = document.getElementById('animal-info'); | |
var btn = document.getElementById('btn'); | |
btn.addEventListener('click',function() { | |
var ourRequest = new XMLHttpRequest(); | |
ourRequest.open('GET','https://learnwebcode.github.io/json-example/animals-' + pageCounter + '.json'); | |
ourRequest.onload = function() { | |
var ourData = JSON.parse(ourRequest.responseText); | |
renderHTML(ourData); | |
}; | |
ourRequest.send(); | |
pageCounter++; | |
if (pageCounter > 3) { | |
btn.classList.add('hide-me'); | |
} | |
}); | |
function renderHTML(data) { | |
let htmlString = ''; | |
data.forEach(elem => { | |
htmlString += '<p>' + | |
elem.name +' is a ' + | |
elem.species + ' is likes ' + | |
elem.foods.likes.map((element,index,array) => { | |
return elem.foods.likes.length > 1 && index !== array.length-1 ? | |
element + ' and' : | |
element; | |
}).join(' ') + | |
'.</p>'; | |
}); | |
animalContainer.insertAdjacentHTML('beforeend', htmlString); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment