使用 jQuery getJSON 在 Reddit 上获取 url 的分数
我正在尝试从 reddit 获取某个 URL 的分数。要添加“与 reddit 共享(计数)”链接:
function redditCounter(url) {
// Get number of counts from reddit JSON api
// $.getJSON('http://www.reddit.com/api/info.json?url='+url+'',
$.getJSON('http://www.reddit.com/api/info.json?url=http://stackoverflow.com/q/811074/1288',
function(data) {
count = 0;
if (data.children.count() > 0) {
first_child = data.children[0];
alert(first_child.score);
}
});
}
当您使用curl 或浏览器调用 url 时,结果如 Reddits API 文档。有一个子数组,其中包含带有数字的分数。
然而,$.getJSON
返回一个空答案,在 firebug 中跨过它时会看到。
这可能是 reddit 的保护方法吗?或者我使用 getJSON 错误?
I am trying to get the score for a certain URL from reddit. To add a "share with reddit (count)" link:
function redditCounter(url) {
// Get number of counts from reddit JSON api
// $.getJSON('http://www.reddit.com/api/info.json?url='+url+'',
$.getJSON('http://www.reddit.com/api/info.json?url=http://stackoverflow.com/q/811074/1288',
function(data) {
count = 0;
if (data.children.count() > 0) {
first_child = data.children[0];
alert(first_child.score);
}
});
}
When you call the url with curl, or your browser, the result is like described in Reddits API documentation. There is a children array and that contains a score with a number.
The $.getJSON
, however, returns an empty answer, seen when stepping over it in firebug.
Is this a protection method by reddit maybe? Or am I using getJSON wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我非常确定您实际上应该期待 JSONP 响应,在这种情况下,我相当确定您应该将
&callback=?
附加到您的 URL。编辑:对于将来偶然发现这个问题的任何人来说,请注意:如果 jQuery 的
getJSON()
遇到格式错误的 JSON 对象,或者在本例中从另一个接收到 JSON 对象,它将默默失败没有 JSONP 填充的域。但是,某些浏览器(例如:Google Chrome)可能会抛出 MIME 类型警告,该警告可以很好地指示您获得的 JSON 对象存在问题。I'm pretty sure you should actually be expecting a JSONP response, in which case I'm fairly certain you should append
&callback=?
to your URL.EDIT: Just a note for anyone that stumbles across this question in the future: jQuery's
getJSON()
will fail silently if it encounters a malformed JSON object or, as in this case, receives a JSON object from another domain without the JSONP padding. However, some browsers (e.g: Google Chrome) may throw a MIME type warning that serves pretty well as an indicator that there's something wrong with the JSON object you're getting.