Skip to content

Instantly share code, notes, and snippets.

@dagolinuxoid
Created February 14, 2017 12:53
Show Gist options
  • Save dagolinuxoid/183d1fd9784300fb24ce3a80559dc356 to your computer and use it in GitHub Desktop.
Save dagolinuxoid/183d1fd9784300fb24ce3a80559dc356 to your computer and use it in GitHub Desktop.
#json #ajax
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