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