开发者

How to return an array made in a child jQuery function from the parent function in Javascript?

I'm using a jQuery json function inside another function, how can I return an array made in the jQuery function as the return value of my parent function?

this is the basic setup

function getFlickrSet(flickr_photose开发者_如何学Pythont_id){
  var images = [];

  images = $.getJSON(url, function(data){ return data; // I HAVE THE DATA HERE };

  return images // I HAVE NO DATA HERE
}
var myImages = getFlickrSet(23409823423423);
alert(myImages); // this gives me nothing

I have set up an example on jsfiddle right here, if you could tell me where my code is wrong, I would greatly appreciate it. Thank you!


You can't. Instead, pass in a function:

function getFlickrSet(flickr_photoset_id, when_ready){
  var images = [];

  $.getJSON(url, function(data){ 
    // prepare images
    when_ready( images );

  });
}

getFlickrSet(nnnn, function(images) {
  alert(images);
});

Why can't you do that? Because the "$.getJSON()" call is asynchronous. By the time that the callback function is called (where you wrote, "I HAVE THE DATA HERE"), the outer function has returned already. You can't make the browser wait for that call to complete, so instead you design the API such that code can be passed in and run later when the result is available.


Well, Ajax is asynchronous (that's what the 'A' stands for), so you must do this in an asynchronous way, which boils down to callbacks. What you need to do is pass a callback function to your outer function that you want to be called ("called back," if you will) when the Ajax request completes. You could just give it 'alert' like this:

function getFlickrSet(flickr_photoset_id) {
  images = $.getJSON(url, alert); // <-- just the name of the function, no ()
}
var myImages = getFlickrSet(23409823423423);
// => An alert pops up with the data!

...but more likely you'd write something like this:

function doSomethingWithData(data) { // we'll use this later
  alert(data); // or whatever you want
}

function getFlickrSet(flickr_photoset_id, callback) {
  // new parameter here for a function ------^
  // to be given here -------v
  images = $.getJSON(url, callback);

  return images // I HAVE NO DATA HERE
}

var myImages = getFlickrSet(23409823423423, doSomethingWithData);
// => Your function `doSomethingWithData` will be called the data as a parameter
//    when the $.getJSON request returns.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜