简体   繁体   English

从 API 获取所有数据

[英]Get All data From API

I just want to print all the data from the API .我只想打印API中的所有数据。 I get the JSON's data from calendarific .我从calendarific获取JSON's数据。 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 ?我刚试过For循环可能是问题在For loop里面?

You can print all the holiday's name by updating the for loop inside renderHTML function like:您可以通过更新renderHTML function 中的for循环来打印所有假期的名称,例如:

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:因为从 API 返回的格式如下:

{
    "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.所以,这里的data实际上并不是一个数组。 It is the data.response.holidays which is an array and we need to loop over it to get all the details. data.response.holidays是一个数组,我们需要遍历它以获取所有详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM