2015-12-15 61 views
1

我是一個新手,應用程序正在處理其他API,尤其是那些需要OAuth身份驗證的應用程序。Reddit API - API與附加.json和獲取首頁信息的區別

現在,我試圖簡單地在我的應用程序中獲取關於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); 

} 

卻得到了一個未定義的:

我想這是案件和審判。有任何想法嗎?

目標是使用console.log(...)而不是alert(...)得到的reddit的JSON響應信息的25頭版(標識)

+0

當獲取JSON時,您只需訪問相關URL並查看您正在處理的JSON對象。只需在瀏覽器中輸入「https:// www.reddit.com/.json」即可。 一旦你有了信息,你就可以隨心所欲地做任何事情。 – thedarklord47

+0

command -f在該頁面上查找「count」顯示JSON blob中沒有稱爲「count」的字段。這就是爲什麼'x.count'未定義的原因。 – thedarklord47

回答

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/

0

嘗試用於顯示信息。打開控制檯(Chrome上的F12)並在那裏查看輸出。

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

xmlHttp.responseText已經是字符串;你正在嘗試對一個字符串進行字符串化。

而是嘗試(如果你只是想看到的文字):

console.log(xmlHttp.responseText); 

或者,如果你想看到的對象:

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