出于学习目的,我正在尝试从开放 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)
的请求数据内容
最佳答案
仅举个例子:如果您自己打开 API Url,您可以看到生成的 data
不是 array
,而是一个 object
如:
{
"response_code": 0,
"results": [
{
"category": "Entertainment: Film",
"type": "multiple",
"difficulty": "medium",
"question": "Who played Batman in the 1997 film "Batman and Robin"?",
"correct_answer": "George Clooney",
"incorrect_answers": [
"Michael Keaton",
"Val Kilmer",
"Christian Bale"
]
}
]
}
这意味着您应该使用 data.results
来迭代数据。
关于javascript - 仅使用 Javascript 从 API 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58447099/