【问题标题】:How to get JSONP to work with jQuery?如何让 JSONP 与 jQuery 一起工作?
【发布时间】:2013-06-30 02:53:24
【问题描述】:

我正在尝试从 Flickr API 获取一些 JSONP 来使用:

http://jsfiddle.net/SRc98/

$.getScript('http://api.flickr.com/services/feeds/photos_public.gne?format=json&tags=cats', function(data, textStatus, jqxhr) {
    alert(data);
});

警报给出undefined,控制台显示:

Uncaught ReferenceError: jsonFlickrFeed is not defined

Flickr API 响应有问题还是有办法让它正常工作?

http://api.flickr.com/services/feeds/photos_public.gne?format=json&tags=cats

【问题讨论】:

  • 因为您的问题与 JSONP(而不是 JSON)有关..请看我的回答..它可能会有所帮助

标签: javascript jquery json jsonp


【解决方案1】:

尝试使用jQuery.getJSON() 代替:

$.getJSON('http://api.flickr.com/services/feeds/photos_public.gne?format=json&tags=cats&jsoncallback=?', function(data, textStatus, jqxhr) {
    alert(data);
});

你可以看到Online API Documentation Demo

编辑:

此处添加了现场演示

// Set the flicker api url here
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";

// Set the tag display options
var options = {
  tags: "cats",
  format: "json"
};

// Get json format data using $.getJSON()
$.getJSON(flickerAPI, options)
  .done(OnApiCallSuccess)
  .fail(OnApiCallError);

// Api call success callback function
function OnApiCallSuccess(data) {
  $.each(data.items, function(i, item) {
    $("<img>").attr("src", item.media.m).appendTo("#images");

    // Load only the first 6 images for demo
    if (i === 6) return false;
  });
}

// Api call error callback function
function OnApiCallError(jqxhr, textStatus, error) {
  var err = textStatus + ", " + error;
  console.log("Request Failed: " + err);
}
img {
  height: 100px;
  float: left;
  padding: 0 10px 10px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div id="images"></div>

【讨论】:

    【解决方案2】:

    JQuery 的 getScript 将数据参数硬编码为 null,并自动评估检索到的脚本。
    我认为文档是错误的。好消息是您可能只是想评估脚本,根本不需要回调。

    对于您的情况:-
    从您的 URL 检索的脚本确实正在评估,但目前没有 function jsonFlickrFeed().so 的定义,这就是显示未定义错误的原因。 您需要包含一些有其定义的 JS 文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-20
      • 2023-02-02
      • 1970-01-01
      相关资源
      最近更新 更多