多个Ajax和非Ajax功能后回调 [英] Callback after multiple ajax and non-ajax functions

查看:146
本文介绍了多个Ajax和非Ajax功能后回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习从两个功能,其中之一是AJAX,一个非AJAX(都是异步的)成功的结果后进行回调。在我的剧本有一个非Ajax调用在程序开始加载多个图像,和一个Ajax(JQuery的)调用请求数据的JSON在脚本中的变量。我发现jQuery的时()功能,使多个Ajax调用,我已经发现的这个答案多份请求回调之前,这可能是容易被破解。我追我的尾巴一下就这一个,并寻找有关是否或如何使一个功能多,混合功能后执行回调一些建议。预先感谢您的想法!

I'm learning to perform a callback after successful results from two functions, one of which is ajax and one is non-ajax (both are asynchronous). In my script there is a non-ajax call to load multiple images at the start of the program, and an ajax (JQuery) call to request a JSON with data for a variable in the script. I've discovered JQuery's when() function for making multiple ajax calls, and I've discovered this answer for making multiple requests before a callback, that might be hackable. I'm chasing my tail a bit on this one and looking for some advice on whether or how to make a function to perform a callback after multiple, mixed functions. Thanks in advance for your thoughts!

推荐答案

$。当实际上将采取多种延期的对象,所以你可以做这样的事情:

$.when will actually take in multiple deferred objects, so you can do something like this:

var xhr = ajax();
var images_promise = loadImages();

$.when.apply($, [xhr, images_promise]).done(function () {
    // something to do when both are complete
});

前提是 AJAX loadImages 函数返回的承诺对象:

Provided that the ajax and loadImages functions return promise objects:

function ajax() { 
    return $.ajax({
        // ajax configuration
    });
}

function loadImages() { 
    // create the deferred promise object
    var dfd = new jQuery.Deferred();
    $("img").on('load', function() { 
        // on the load event resolve the promise
        dfd.resolve();
    });
    return dfd;
}

了解更多关于推迟承诺这里

这篇关于多个Ajax和非Ajax功能后回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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