我正在通过JS向https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=API-KEY-HERE发送GET请求,它可以工作。虽然,我绝对不知道如何解析弹出的长JSON。我想获得第一篇文章的标题。

码:

var HttpClient = function () {
   this.get = function (aUrl, aCallback) {
       var anHttpRequest = new XMLHttpRequest();
       anHttpRequest.onreadystatechange = function () {
           if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
               aCallback(anHttpRequest.responseText);
       }

       anHttpRequest.open("GET", aUrl, true);
       anHttpRequest.send(null);
    }
}
var client = new HttpClient();
client.get('https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=08f3b70e722d46ebab1fdd5b5499f671', function (response) {
    console.log(response);
});


编辑:我尝试使用console.log(response['articles'][0]);,但返回错误

最佳答案

使用JSON.parse

var client = new HttpClient();
client.get('https://newsapi.org/v1/articles?source=google-news&sortBy=top&apiKey=<your-api-key-here>', function (response) {
    var json = JSON.parse(response);

    console.log(json['articles'][0]);
});

09-18 13:25