【问题标题】:Reddit API - difference between API and appending .json and getting front page infoReddit API - API 和附加 .json 以及获取首页信息之间的区别
【发布时间】:2016-03-20 17:05:25
【问题描述】:

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

目前,我正在尝试在我的应用程序中获取有关 Reddit 头版列表的信息。

我正在查看此 Reddit API 文档 here,但随后我正在阅读该文档以获取 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 页面上的 LAST 帖子,或者我无法判断,因为警报框无法显示巨大的 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响应信息(标识符)

【问题讨论】:

  • GETing JSON 时,您可以简单地访问相关 URL 并查看您正在处理的 JSON 对象。只需在浏览器中输入https://www.reddit.com/.json。有了这些信息,您就可以随心所欲地做任何事情。
  • command-f 在该页面上查找“count”表明 JSON blob 中没有名为 count 的字段。这就是 x.count 未定义的原因。

标签: javascript jquery json api reddit


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

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

    试试看(如果你只想看文字):

    console.log(xmlHttp.responseText);
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-23
      • 2013-12-03
      • 2011-05-20
      • 2021-04-03
      • 1970-01-01
      相关资源
      最近更新 更多