Reddit API - API 与附加 .json 和获取首页信息之间的区别

Reddit API - difference between API and appending .json and getting front page info

我是制作处理其他 API 应用程序的新手,尤其是那些需要 OAuth 身份验证的应用程序。

目前,我只是想在我的应用程序中获取有关 Reddit 首页列表的信息。

我正在查看这个 Reddit API 文档 here,但后来我正在阅读它以获得 Reddit 的 JSON 表示,您只需添加一个 .json 在 url 之后。

所以我正在发送一个 HTTP GET 请求,例如:

$(document).ready(function () {

    httpGetAsync("https://www.reddit.com/.json");

});

function httpGetAsync(url) {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            alert(JSON.stringify(xmlHttp.responseText, null, 4));
    }
    xmlHttp.open("GET", url, true); // true for asynchronous 
    xmlHttp.send(null);
}

但这似乎只返回 reddit 页面上似乎是最后一个 post 的内容,或者我可能无法分辨,因为警告框无法显示巨大的 JSON 响应?

我认为是这种情况并尝试过:

var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
        parseResponse(xmlHttp.responseText);
}
xmlHttp.open("GET", url, true); // true for asynchronous 
xmlHttp.send(null);


function parseResponse(responseText) {
var x = (JSON.parse(responseText));
alert(x.count);

}

但在警告框中出现未定义。有任何想法吗?

目标是获取reddit的第25页JSON回复信息(标识符)

尝试使用 console.log(...) 而不是 alert(...) 来显示信息。打开控制台(Chrome 上的 F12)并查看那里的输出。

JSON.stringify(xmlHttp.responseText, null, 4)

xmlHttp.responseText 已经是一个字符串;您正在尝试对字符串进行字符串化。

改为尝试(如果您只想查看文本):

console.log(xmlHttp.responseText);

或者如果你想看对象:

console.log(JSON.parse(xmlHttp.responseText));

您可能想要使用 jQuery 来检索和解析数据:

$.getJSON( "https://www.reddit.com/.json", function( data ) {
  $.each( data.data.children, function( i, obj ) {
     console.log(obj.data.id);
  });
});

我为您制作了一个检索前 25 个 ID 的工作示例:

https://jsfiddle.net/enmpw8qf/