如何使JSONP与jQuery一起使用? [英] How to get JSONP to work with jQuery?

查看:126
本文介绍了如何使JSONP与jQuery一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to get some JSONP from the Flickr API to work with:

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,控制台显示:

The alert gives undefined and the console says:

Uncaught ReferenceError: jsonFlickrFeed is not defined

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

Is there something wrong with the Flickr API response or is there a way to get this to work after all?

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

推荐答案

尝试使用 jQuery.getJSON() 相反:

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

您可以查看在线API文档演示

在此处添加了现场演示

// 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>

这篇关于如何使JSONP与jQuery一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆