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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8191105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:02:32  来源:igfitidea点击:

How to extract url data from Reddit API using JSON

javascriptjsonapireddit

提问by izolate

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

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

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

一段时间以来,我一直试图将 jQuery Docs 中的.getJSON()Flickr 示例组合在一起,但我一无所获。

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

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

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

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

回答by pradeek

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 fiddlein 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.childrenand not data.children

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