javascript - 仅使用 Javascript 从 API 获取数据

标签 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();

编辑显示来自console.log(data)的请求数据内容

Result of console.log()

最佳答案

仅举个例子:如果您自己打开 API Url,您可以看到生成的 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 来迭代数据。

关于javascript - 仅使用 Javascript 从 API 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58447099/

相关文章:

java - Intent.setData 与 Intent.putExtra

java - 盈透证券 API 和 Web 应用程序

android - 任何适用于土耳其语的 Android TTS api?

objective-c - iPhone App通过LinkedIn API授权后无法确认

javascript - 如何存储对象数组?

javascript - 如果字符串同时包含数字和字母,如何按字母顺序对字符串进行排序?

javascript - 升级到 Node 0.10 后的问题

android - 谷歌端点使用带有本地 HTTP API 的资源管理器

javascript - 如何在刷新时开始编号

javascript - Jquery:如何在按下回车键或单击按钮时触发单击事件