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

时间:2015-12-15 02:39:53

标签: javascript jquery json api reddit

我是处理其他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页面上的最新帖子,或者我无法分辨,因为警报框无法显示巨大的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页

2 个答案:

答案 0 :(得分:1)

尝试使用def primeNumbers(num): primes = [] i = 2 # iterates through range from 2 to num(inclusive) while i <= num : # add 'while' condition k = 2 isPrime = True # check if prime number while k * k < num : # add 'while' condition if i%k==0: isPrime = False k +=1 # update k if isPrime: primes.append(i) i +=1 # update i return primes 代替console.log(...)来显示信息。打开控制台(Chrome上的F12)并在那里查看输出。

alert(...)

JSON.stringify(xmlHttp.responseText, null, 4) 已经是一个字符串;你正在尝试对字符串进行字符串化。

相反尝试(如果你只是想看文字):

xmlHttp.responseText

或者如果你想看到对象:

console.log(xmlHttp.responseText);

答案 1 :(得分: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/