How to get JSONP to work with jQuery?

笑着哭i 提交于 2019-12-14 03:17:56

问题


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

The alert gives undefined and the console says:

Uncaught ReferenceError: jsonFlickrFeed is not defined

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


回答1:


Try using jQuery.getJSON() instead like:

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

You can see the Online API Documentation Demo

EDIT:

Live demo added here

// 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's getScript hardcodes data parameter to null, and automatically evaluates the retrieved script.
I think documentation is wrong. Good thing is that you probably just wanted to evaluate the script anyway and you dont need the callback at all.

For your Case:-
script retreived from your URL is indeed getting evaluated but currently there is no definition for function jsonFlickrFeed().so that's why undefined error is shown. You need to include some JS file which has its definition.



来源:https://stackoverflow.com/questions/17430666/how-to-get-jsonp-to-work-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!