在JSON.parse中获取“ JSON输入意外结束”

时间:2019-05-02 21:36:56

标签: javascript json xml

仅收到语法错误,“ JSON.parse处的JSON输入意外结束”

var trivia;
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var request = new XMLHttpRequest();

request.open('GET', 'https://opentdb.com/api.php?amount=5&category=15&difficulty=easy&type=boolean');
 request.send();

trivia = JSON.parse(request.responseText);
console.log(trivia);

1 个答案:

答案 0 :(得分:1)

问题是您需要等待响应到达才能继续。您可以使用AJAX请求的onload事件来实现这一目标:

var trivia;
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var request = new XMLHttpRequest();

request.open('GET', 'https://opentdb.com/api.php?amount=5&category=15&difficulty=easy&type=boolean');


request.onload = function() {
    trivia = JSON.parse(request.responseText);
    console.log(trivia);
}

request.send();