Reputation: 1722
I just want to print all the data from the API
. I get the JSON's
data from calendarific. I am only able to print specific data but what can I do to print all the data? Here is what I tried
btn.addEventListener('click', function() {
var newRequest = new XMLHttpRequest();
newRequest.open('GET', 'https://calendarific.com/api/v2/holidays?&api_key=<myKey>&country=US&year=2019')
newRequest.onload = function() {
var ourData = JSON.parse(newRequest.responseText);
// para.innerHTML = ourData.response.holidays[407].name
// console.log(ourData.response.holidays[407].name)
renderHTML(ourData)
}
newRequest.send();
});
function renderHTML(data) {
var htmlString = '';
for (i = 0; i < data.length; i++) {
htmlString += '<p>' + data[i].response.holidays[0].name + '</p>'
}
//i want to show inside paragraph whose id is para
para.insertAdjacentHTML('beforeend', htmlString)
}
I just tried the For
loop may be Problem is in inside For loop
?
Upvotes: 2
Views: 1118
Reputation: 73956
You can print all the holiday's name by updating the for
loop inside renderHTML
function like:
for (var i = 0; i < data.response.holidays.length; i ++) {
htmlString += '<p>' + data.response.holidays[i].name + '</p>'
}
because format returned from API is like:
{
"meta": {
"code": 200
},
"response": {
"holidays": [
{
"name": "Name of holiday goes here",
"description": "Description of holiday goes here",
"date": {
"iso": "2018-12-31",
"datetime": {
"year": 2018,
"month": 12,
"day": 31
}
},
"type": [
"Type of Observance goes here"
]
}
]
}
}
So, data
is not actually an array here. It is the data.response.holidays
which is an array and we need to loop over it to get all the details.
Upvotes: 3