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

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

本文关键字:首页 获取 信息 区别 json API-API Reddit      更新时间:2023-09-26

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

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

我在这里看到的是这个Reddit API文档,但我读到的是,要获得Reddit的JSON表示,你只需要在url后面添加一个.JSON。

所以我发送了一个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页面上的最后一篇帖子,或者我可能无法判断,因为警报框无法显示巨大的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 JSON响应信息(标识符)的25个首页

您可能需要使用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/

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

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

xmlHttp.responseText已经是一个字符串;你想把绳子串起来。

相反,尝试(如果你只想看到文本):

console.log(xmlHttp.responseText);

或者,如果您想查看对象:

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