admin管理员组

文章数量:1278789

So I've written some code that searches reddits api based on a query and I want it to display ments as well. I have the following code nested inside my $.getJSON statement that pulls each title/post based on your search query, and now I want to display the ment tree for each result thats found (hence why I have it nested in my original getJSON statement)

$.getJSON("/" + sub + "/ments/" + id + ".json?", function (data){
  $.each(data.data.children, function (i, item) {
    var ment = item.data.body
    var author = item.data.author
    var postment = '<p>[Author]' + author + '<br>' + ment + '</p>'
    results.append(postment)
  });
});

I have a feeling I may be structuring the $.each statement wrong or something. I'm just following what I did for the other getJSON statement. Any ideas?

So I've written some code that searches reddits api based on a query and I want it to display ments as well. I have the following code nested inside my $.getJSON statement that pulls each title/post based on your search query, and now I want to display the ment tree for each result thats found (hence why I have it nested in my original getJSON statement)

$.getJSON("http://www.reddit./r/" + sub + "/ments/" + id + ".json?", function (data){
  $.each(data.data.children, function (i, item) {
    var ment = item.data.body
    var author = item.data.author
    var postment = '<p>[Author]' + author + '<br>' + ment + '</p>'
    results.append(postment)
  });
});

I have a feeling I may be structuring the $.each statement wrong or something. I'm just following what I did for the other getJSON statement. Any ideas?

Share Improve this question edited Feb 5, 2014 at 14:27 Andy 63.6k13 gold badges71 silver badges98 bronze badges asked Feb 5, 2014 at 14:25 mickdeezmickdeez 5113 gold badges8 silver badges20 bronze badges 1
  • I also noticed on JSONViewer that when I use the url to retrieve ments, it pulls [0] and [1], 0 having the original data for the post, and 1 having the data for the ments. Maybe I need to specify to look at [1]? – mickdeez Commented Feb 5, 2014 at 14:31
Add a ment  | 

1 Answer 1

Reset to default 9

The reddit json contains two objects: the post, and the ments. The ments are located at data[1] This should work:

$.getJSON("http://www.reddit./r/" + sub + "/ments/" + id + ".json?", function (data){
  $.each(data[1].data.children, function (i, item) {
    var ment = item.data.body
    var author = item.data.author
    var postment = '<p>[Author]' + author + '<br>' + ment + '</p>'
    results.append(postment)
  });
});

本文标签: javascriptRetrieving comments from Reddit39s APIStack Overflow