如何使用 JSON 从 Reddit API 中提取 url 数据

问题描述:

我正在尝试从 subreddit 提要中提取图片帖子 URL,并在我的页面上呈现 <img> 元素.

I'm trying to extract the image post URLs from a subreddit feed, and render <img> elements on my page.

一直在尝试破解 .getJSON() Flickr 示例 来自 jQuery Docs 一段时间了,我什么也没有.

Been trying to hack together the .getJSON() Flickr example from the jQuery Docs for a while now and I'm not getting anywhere.

有问题的代码:

$.getJSON('http://www.reddit.com/r/pics.json', function (data) {
  $.each(data.children, function (i, item) {
    $('<img/>').attr("src", url).appendTo("#images");
  });
});

在正文中,我有元素:div#images

我知道我需要使用 JSONP,但不确定如何使用.有人能指出我正确的方向吗?

I understand that I need to use JSONP, but not sure how. Can somebody point me in the right direction?

您使用了错误的网址.使用这个:

You are using the wrong url. Use this:

$.getJSON("http://www.reddit.com/r/pics/.json?jsonp=?", function(data) { 
    // Do whatever you want with it.. 
});

基于您在评论中的fiddle的工作示例.>

EDIT : Working example based on your fiddle in the comments.

$.getJSON("http://www.reddit.com/r/pics/.json?jsonp=?", function(data) { 
    $.each(data.data.children, function(i,item){
        $("<img/>").attr("src", item.data.url).appendTo("#images");
    });
});

你应该使用 data.data.children 而不是 data.children

You should use data.data.children and not data.children