仅使用Javascript从API获取数据

时间:2019-10-18 08:41:25

标签: javascript api

出于学习目的,我试图从开放的API中获取数据以进行测验。

我开始的工作是从API获取数据,然后在console.log()中查看我的操作是否正确。 我正在解析foreach之前的URL,但出现错误:

Uncaught TypeError: data.forEach is not a function

这是我正在尝试的示例代码,我了解我必须先在foreach之前解析JSON,但对我不起作用并且无法理解原因

/**
 *
 * @GET url of the API https://opentdb.com
 *
 */
// Creating a request variable with the OBJ inside
var request = new XMLHttpRequest();
// Opening a GET request to the API
request.open("GET", "https://opentdb.com/api.php?amount=10");
// Load the request
request.onload = function() {
    // Accessing the JSON data
    var data = JSON.parse(this.response);
    // Checking if we have status 200 good to go otherwise error
    if (request.status >= 200 && request.status < 400) {
        // Looping the data
        data.forEach(results => {
            console.log(results.question);
        });
    } else {
        // Showing error for the status
        console.log("error");
    }
};
// Request send
request.send();

EDIT显示来自console.log(data)的询问数据内容

Result of console.log()

6 个答案:

答案 0 :(得分:3)

仅以您的示例为例:如果您自己打开API网址,则可以看到生成的data不是array,而是object,例如:

{
    "response_code": 0,
    "results": [
        {
            "category": "Entertainment: Film",
            "type": "multiple",
            "difficulty": "medium",
            "question": "Who played Batman in the 1997 film &quot;Batman and Robin&quot;?",
            "correct_answer": "George Clooney",
            "incorrect_answers": [
                "Michael Keaton",
                "Val Kilmer",
                "Christian Bale"
            ]
        }
    ]
}

这意味着您应该使用data.results来遍历数据。

答案 1 :(得分:1)

您从服务器获取的数据是一个对象,而不是数组。 .forEach仅在阵列上可用。

但是在数组内部 中,该数据称为“结果”,其中的对象包含您感兴趣的“问题”属性。

因此修复很简单,只需遍历“结果”数组即可:

data.results.forEach(result => {
  console.log(result.question);
});

答案 2 :(得分:1)

  var data = JSON.parse(this.response);
    // Checking if we have status 200 good to go otherwise error
    if (request.status >= 200 && request.status < 400) {
        // Looping the data
        data.forEach(results => {
            console.log(results.question);
        });
    } else {
        // Showing error for the status
        console.log("error");
    }
};

由于您的数据不是数组,因此不能重复,并且forEach函数用于遍历数组。 假设您的响应包含任何数组

 responseData: {
                sc: "0000|Success",
                 clientId: "ptm",
                  reportStatus:[
                      {reportName: "sale_report", 
                          id: "275", 
                          status: "AVAILABLE"},
                          {reportName: "sale_report", 
                          id: "276", 
                          status: "PENDING"}]
}

responseData.reportStatus获取该值,然后对其进行迭代。

responseData.reportStatus.forEach((item,index,arr)=>{
  console.log(item);
})

这将获取数组中的所有项目。

答案 3 :(得分:1)

我实际上已经修改了代码,您正在循环使用错误的属性,而您应该在结果上循环。

 var request = new XMLHttpRequest();
    // Opening a GET request to the API
    request.open("GET", "https://opentdb.com/api.php?amount=10");
    // Load the request
    request.onload = function() {
      // Accessing the JSON data
      var response = JSON.parse(this.response);

      // Checking if we have status 200 good to go otherwise error
      if (request.status >= 200 && request.status < 400) {
        // Looping the data
        var data = response.results;
        data.forEach(results => {
          console.log(results.question);
        });
      } else {
        // Showing error for the status
        console.log("error");
      }
    };
    // Request send
    request.send();

工作代码在下面   https://codesandbox.io/s/white-breeze-8w8jy

答案 4 :(得分:1)

return [
    'db' => [
        'username' => 'root',
        'password' => 'root',
    ]
];

我已经尝试过您的代码,但是您缺少数据和forEach之间的结果。 之后,它正在控制台中记录问题。

答案 5 :(得分:0)

似乎您正在访问整个响应,而是获得结果this.response.results

var data = JSON.parse(this.response).results;

if (request.status >= 200 && request.status < 400) {
    data.forEach(results => {
        console.log(results.question);
    });
}