等到所有ajax请求完成 [英] Wait until all ajax requests are done

查看:92
本文介绍了等到所有ajax请求完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要等到我的所有ajax功能都完成,然后继续执行exectution。

I need to wait until all my ajax functions are done, and then continue the exectution.

我的特殊情况是我需要翻译表单中的某些字段在提交之前。我通过对外部站点的ajax调用来翻译它们。根据表单中的某些值,我需要做更多或更少的翻译。完成所有翻译后(如果有的话)我必须用ajax验证表单,如果有效,则提交。

My particular case is that I need to translate some fields in a form before submitting it. I translate them with an ajax call to an external site. Depending on some values in the form i would need to do more or less translations. When all the translations are done (if any) I have to validate the form with ajax, and if its valid, then submit.

这是我的方法:

首先,我有一个函数发送ajax调用并对收到的数据做一些事情:

This is my aproach:
First, I have a function that sends the ajax call and do stuff with the data received:

function translate(...) {
    $("#ajaxCounter").val(parseInt($("#ajaxCounter").val()) + 1);
    $.ajax({
        ...
        success:function(data) {
            ...
            $("#ajacCounter").val(parseInt($("#ajaxCounter").val()) - 1);
        }
    });

然后,当要提交表单时,我执行以下代码:

Then, when the form is to be submitted I execute the following code:

$("#form").submit(function() {
    translatable_fields.each(function() {
        translate(...);
    });
    while (parseInt($("#ajaxCounter").val()) > 0) { null; }
    if (!(this).hasClass('ready')) {
        $.ajax({
            //validation
            success: function(data) {
                if (data['isValid']) {
                    $("#form").addClass('ready');
                    $("#form").submit();
                }
            }
        });
    }
    return true;
});

问题是循环提交函数永远不会结束。

The problem is that the while loop in the submit function never ends.

如果我在没有的情况下执行代码,而循环我可以看到 ajaxCounter 输入在翻译函数开始时增加,在结束时减少。

If I execute the code without the while loop I can see the ajaxCounter input increasing when the translation functions start and decreasing when they end.

推荐答案

你可以使用从 $。ajax 调用返回的 deferred 对象以更整洁的方式实现此目的。首先你应该得到 translate()函数来返回 deferred

You can achieve this in a much neater fashion using the deferred objects returned from a $.ajax call. First you should get the translate() function to return the deferred:

function translate(...){
    return $.ajax({
        // settings...
    });
});

然后你可以把所有这些承诺放到一个数组中:

Then you can put all those promises in to a single array:

var requests = [];
translatable_fields.each(function(){
    requests.push(translate(...));
});

然后你可以该数组应用于 $。当

Then you can apply that array to $.when:

$.when.apply($, requests).done(function(schemas) {
     console.log("All requests complete");
    // do something...
});

这篇关于等到所有ajax请求完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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