grabbing Reddit data via javascript

2019-05-27 09:48发布

问题:

I came across this post, which is pretty much what I'm looking to do:

How to extract url data from Reddit API using JSON

I have modified the jsfiddle that was provided (NSFW http://jsfiddle.net/DHKtW/170/) to read:

$.getJSON("http://www.reddit.com/r/pics/.json?jsonp=?", function(data) {
  $.each(data.data.children, function(i,item){
    console.log($('.score.likes').html(item));
  });
});

My goal is to gather the total amount of upvotes on a given page. When you run this and look at the console, objects are being returned but not the actual number. I thought just calling html on the selector would return the number of votes but apparently am wrong. Any better way of doing this?

回答1:

You need to console.log(item) to see the returned data. Using that we can then see that item.data.score returns the score of a post.

$.getJSON("http://www.reddit.com/r/pics/.json?jsonp=?", function (data) {
    $.each(data.data.children, function (i, item) {
        console.log(item.data);
        $('<div/>', {
            text: 'Post ' + item.data.permalink + ' has a score of ' + item.data.score
        }).appendTo('#images');
    });
});

http://jsfiddle.net/DHKtW/353/

The reason you saw objects without number is because you called console.log($('selector')) and that returns the jQuery object not the json from the request.