javascript - 使用 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;
}
解决方案
推荐阅读
- ubuntu - Ubuntu 18.04 LTS 中不存在 conf php7.1-cgi
- javascript - 等到请求以角度完成
- android - 快速更改底部导航应用程序崩溃
- php - 同一日期只显示一个分隔符时的SQL查询
- docker - elasticsearch kubernetes pod的Back-off重启失败容器的原因是什么?
- php - Instagram API 仅显示 foreach 循环中的第一项
- angular - 表中带有分页组件的问题
- python - Tensorflow 神经网络的简单回归误差非常高
- swift - 更改 UIAlertController 的标题字体大小
- ruby-on-rails - Trix 格式化规则