使用newsapi时,我收到错误“Uncaught SyntaxError:JSON输入的意外结束”

时间:2018-05-19 18:06:20

标签: javascript json ajax

基本上,我将输出的JSON放入变量然后将其解析为对象,但解析器不起作用。 (对不好的缩进,我是新的堆栈溢出)

var url = 'https://newsapi.org/v2/top-headlines?' +
      'country=us&' +
      'apiKey=lol_dont_take_my_api_key';
var jsonString = "";
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
 //document.getElementById("placeholder").innerHTML = this.responseText;// + "}]}";
    jsonString = this.response;
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
loadDoc();
console.log(jsonString);
var obj = JSON.parse(jsonString);
if (obj.status == "ok") {
var articles = obj.articles;
} else {
console.log("error");
}
var i;
for (i = 0; i < articles.length; i++) {
    document.getElementById("main").innerHTML += articles[i].title;
}

0 个答案:

没有答案