简体   繁体   中英

Getting "Unexpected end of JSON input at JSON.parse

Just getting a Syntax Error, "Unexpected end of JSON input at JSON.parse"

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);

The problem is that you need to wait for the response to arrive before continuing on. You can achieve just that using the AJAX request's onload event:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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