14

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

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

Code in question:

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

In the body, I have the element: div#images

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

izolate
  • 1,590
  • 4
  • 22
  • 35

2 Answers2

22

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.. 
});

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");
    });
});

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

tw16
  • 29,215
  • 7
  • 63
  • 64
pradeek
  • 21,445
  • 2
  • 31
  • 32
  • @ZachL I tried running your fiddle and it isn't working either. I'm not having issues extracting what I want from the data variable. My function never even gets called. – Talon876 Jul 20 '13 at 13:54
  • @ZachL It appears to be working in Firefox but not Chrome on OSX 10.8.4. – Talon876 Jul 20 '13 at 14:00
  • @Talon876 [Glad you sorted it out](http://www.reddit.com/r/webdev/comments/1ioezx/reddit_api_and_jsonp_not_working/) (the problem was adblock.) – Zach Lysobey Jul 20 '13 at 14:22
0

For internet friends being lost here:

fetch("http://www.reddit.com/r/pics/.json")
  .then(r => r.json()).then((r) => {
     r.data.children.forEach((i) => {
       try{
         document.body.appendChild(Object.assign(document.createElement("img"),{src: i.data.thumbnail}))
       } catch (error){console.log(error.message)}
 })})
NVRM
  • 11,480
  • 1
  • 88
  • 87