如何从 JavaScript 中的父函数返回在子 jQuery 函数中创建的数组?

问题描述 投票:0回答:2

我在另一个函数中使用 jQuery JSON 函数,如何返回 jQuery 函数中创建的数组作为父函数的返回值?

这是基本设置:

function getFlickrSet(flickr_photoset_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

我在 JS Fiddle 上设置了一个示例。我的代码哪里不正确?

javascript jquery json function return
2个回答
4
投票

你不能。相反,传入一个函数:

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

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

  });
}

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

为什么你不能这样做?因为“$.getJSON()”调用是异步。当回调函数被调用时(你写的“我这里有数据”),外部函数已经返回。您无法让浏览器等待该调用完成,因此您需要设计 API,以便可以传入代码并在结果可用时运行。


1
投票

Ajax 是异步的(这就是“A”代表的意思),因此您必须以异步方式执行此操作,这可以归结为回调。您需要做的是将回调函数传递给您希望在 Ajax 请求完成时调用的外部函数(如果愿意,可以称为“回调”)。你可以像这样给它“警报”:

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!

...但更有可能你会写这样的东西:

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.
© www.soinside.com 2019 - 2024. All rights reserved.