Can't store data fetched with jQuery JSONP

痴心易碎 提交于 2019-12-10 10:37:39

问题


I'm trying to fetch a bunch of photo data from Flickr via a jQuery AJAX call using JSONP, but I don't want to use the data right away. Instead, I'd like to preserve it for use later. In a complicated case, I'd like to let users perform different queries on the prefetched data. In a simpler case, I'd like to just load the next n images each time the user clicks a button.

Right now, I'm testing just the most basic functionality below, which is adapted from the best answer to this question: JQuery - Storing ajax response into global variable

However, the retrieved JSON data is not getting stored in the jsonData variable as it should. I put the alert statements to debug, and the strange thing is that the getData() alert is triggered before the alert in the callback function. Why is this happening?

var dataStore = ( function() {
  var jsonData;

  $.ajax({
    type: "GET",
    url: "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
    dataType: "json",
    data: {
      tags: "dog",
      tagmode: "any",
      format: "json"
    },
    success: function(data) {
      jsonData = data;
      alert(jsonData);
    }
  });

  return { getData : function()
  {
      if (jsonData) return jsonData;
      else alert("no data!");
  }};
})();

var stuff = dataStore.getData();

$.each(stuff.items, function(i,item) {
  $("<img/>").attr("src", item.media.m).appendTo("#images");
  if ( i == 3 ) return false;
});

回答1:


...and the strange thing is that the getData() alert is triggered before the alert in the callback function. Why is this happening?

Because ajax calls in general are, by default, asynchronous — and JSONP calls are always asynchronous by their nature (other kinds of ajax calls can be made synchronous, but it's generally a bad idea).

This means your

var stuff= dataStore.getData();

line executes before the JSONP request completes. This is also why it doesn't see anything in jsonData.

You need to move any processing of the JSONP call result into something called from the success callback of the request.




回答2:


The problem is that stuff is undefined when $.each runs because stuff hasn't finished running yet. Everything needs to be in a callback. There's numerous ways to get around it from the most ugly and hacky of doing a setInterval() that checks if stuff === undefined and if NOT then it does the $.each to a more JS native way of just using callbacks.

Personally, I highly suggest you just use callbacks more effectively. Here's what i'd do. This should put you on the right track. Obviously a lot of this is faux code, but can easily be modified to your needs.

var cachedImageData = {}; //To check if data exists for the search term

var displayImages = function(stuff){
  $.each(stuff.items, function(i,item) {
    $("<img/>").attr("src", item.media.m).appendTo("#images");
    if ( i == 3 ) return false;
  });
}

$('button').bind('click',function(){ //Triggers the ajax...
  if(cachedImageData[$('input').val()] === undefined){ //If this search doesn't exist...
    $.ajax({
      url:''
      data:{ tag: $('input').val() }, //Get the value however
      success: function(data){
        cachedImageData[$('input').val()] = data; //Save for later
        displayImages(data); //Run the display images function which is your $.each()
      }
    });
  }
});


来源:https://stackoverflow.com/questions/8353374/cant-store-data-fetched-with-jquery-jsonp

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