首页 > 解决方案 > 使用 newsapi 时,我收到错误“Uncaught SyntaxError: Unexpected end of JSON input”

问题描述

基本上,我将输出的 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;
}

标签: javascriptjsonajax

解决方案


推荐阅读