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

How to extract url data from Reddit API using JSON

本文关键字:提取 url 数据 API Reddit 何使用 JSON      更新时间:2023-09-26

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

一直试图破解.getJSON() Flickr的例子从jQuery文档现在一段时间,我没有得到任何地方。

问题代码:

$.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,但不确定如何使用。有人能给我指个正确的方向吗?

您使用了错误的url。使用这个:

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

编辑:基于您的小提琴在评论中的工作示例。

$.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

网上迷路的朋友:

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