未捕获的ReferenceError:未定义jsonFlickrFeed

时间:2018-04-07 13:34:56

标签: javascript ajax request flickr

我有以下要求:

const flickrApiPoint = "https://api.flickr.com/services/feeds/photos_public.gne";

try {

  $.ajax({
    url: flickrApiPoint,
    dataType: 'jsonp',
    data: { "format": "json" },
    success: function (data) {
      console.log(data); //formatted JSON data
    }
  });
}
catch (e) {
  console.log(e);
}

但最终我得到了

Uncaught ReferenceError: jsonFlickrFeed is not defined
    at photos_public.gne?&callback=jQuery331016421245174669186_1523107884637&format=json&_=1523107884638:1

我做得不对,我该如何解决?提前谢谢!

3 个答案:

答案 0 :(得分:1)

您的网址flickrApiPoint不完整。它必须是const flickrApiPoint = "https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";

完整示例:

const flickrApiPoint = "https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";

    try {

          $.ajax({
            url: flickrApiPoint,
            dataType: 'jsonp',
            data: {format: "json"},
            success: function (data) {
              console.log(data); //formatted JSON data
            }
      });
    }
    catch (e) {
      console.log(e);
    }

答案 1 :(得分:1)

因为您正在使用 jsonp ajax调用,所以flickr服务会返回对该函数的调用: jsonFlickrFeed 这意味着您必须自己在代码中定义如下函数:

function jsonFlickrFeed(json) {
    console.log(json);

    $.each(json.items, function (i, item) {
        $("<img />").attr("src", item.media.m).appendTo("#images");
    });
}

这样的功能在ajax上自动执行。因此,您需要定义一个jsonFlickrFeed函数回调,而不是成功的ajax回调。

function jsonFlickrFeed(json) {
    //console.log(json);
    console.log('jsonFlickrFeed called');

    $.each(json.items, function (i, item) {
        $("<img />").attr("src", item.media.m).appendTo("#images");
    });
}
const flickrApiPoint = "https://api.flickr.com/services/feeds/photos_public.gne";

try {

    $.ajax({
        url: flickrApiPoint,
        dataType: 'jsonp',
        data: { "format": "json" },
        complete: function (data) {
            console.log('ajax call completed'); //formatted JSON data
        }
    });
}
catch (e) {
    console.log(e);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="images"></div>

答案 2 :(得分:0)

使用参数nojsoncallback=1仅获取JSON对象。

const flickrApiPoint = "https://api.flickr.com/services/feeds/photos_public.gne?nojsoncallback=1";