【发布时间】: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