jQuery - 在所有ajax完成后执行操作

时间:2013-12-14 13:53:34

标签: javascript jquery ajax

我已经阅读了jQuery的Deferred对象,但我似乎没有多大意义,这是我的问题,我有以下代码:

function preprocess(form) {
    $(form).find(".input input").each(function() {
        var required = $(this).attr("required");
        var checkField = $(this).closest(".inputcontainer").children(".check");
        var errorField = $(this).closest(".inputcontainer").children(".errormessage");
        if (typeof required !== 'undefined') {
            $(checkField).each(function() {
                $(this).css("color", "#FFFF00");
                $(this).html("✘");
            });
            $(errorField).each(function() {
                $(this).css("color", "#FFFF00");
                $(this).html("(Required)");
            });
        }
        else {
            $(checkField).each(function() {
                $(this).css("color", "#FFFF00");
                $(this).html("✔");
            });
            $(errorField).each(function() {
                $(this).css("color", "#000000");
                $(this).html("");
            });
        }
    });

    $(form).find("datalist").each(function() {
        var datalist = $(this);
        callService({
            name: "datalist_" + $(this).attr("id"),
            data: { },
            success: function(json) {
                $(json).each(function() {
                    var html = "";
                    $(this.options).each(function() {
                        html += "<option value='" + this.value + "'>";
                    });
                    $(datalist).append(html);
                });
            }
        });
    });

    $(form).find("select").each(function() {
        var select = $(this);
        callService({
            name: "select_" + $(this).attr("name"),
            data: { },
            success: function(json) {
                $(json).each(function() {
                    var html = "";
                    $(this.options).each(function() {
                        html += "<option value='" + this.id + "'>" + this.value + "</option>";
                    });
                    $(select).append(html);
                });
            }
        });
    });
}

此代码准备一个表单以准备呈现给用户,其中涉及AJAX调用,我已将其包含在callService({});调用中,您可以看到以下内容:

  • 检查输入并在字段旁放置(Required)。 (没有AJAX)
  • 它会动态加载<datalist><select>的选项。 (AJAX)

然后我也有以下(简化):

function setContent(html, url) {
    html = $.parseHTML(html);
    $(html).filter("form").each(function() {
        preprocess($(this));
    });
    $("#pagemain").html(html);
}

这会从AJAX调用中获取html,然后在其所有表单上调用preprocess并更新#pagemain。 但是现在数据显示 preprocess已完全结束。

问题:如何在$("#pagemain").html(html);涉及AJAX流程后preprocessed完成?

3 个答案:

答案 0 :(得分:2)

尝试:

function preprocess(form) {
    //Your above code is omitted for brevity
    var promises = [];

    $(form).find("datalist").each(function() {
        var defered = $.Deferred();//create a defered object
        promises.push(defered.promise());//store the promise to the list to be resolved later

        var datalist = $(this);
        callService({
            name: "datalist_" + $(this).attr("id"),
            data: { },
            success: function(json) {
                $(json).each(function() {
                    var html = "";
                    $(this.options).each(function() {
                        html += "<option value='" + this.value + "'>";
                    });
                    $(datalist).append(html);
                });
                defered.resolve();//resolve the defered when ajax call has finished
            }
        });
    });

    $(form).find("select").each(function() {
        var defered = $.Deferred();//create a defered object
        promises.push(defered.promise());//store the promise to the list to be resolved later
        var select = $(this);
        callService({
            name: "select_" + $(this).attr("name"),
            data: { },
            success: function(json) {
                $(json).each(function() {
                    var html = "";
                    $(this.options).each(function() {
                        html += "<option value='" + this.id + "'>" + this.value + "</option>";
                    });
                    $(select).append(html);
                });
                defered.resolve();//resolve the defered when ajax call has finished
            }
        });
    });
    return promises;
}

您的setContent

function setContent(html, url) {
    html = $.parseHTML(html);
    var promises = [];
    $(html).filter("form").each(function() {
        promises = promises.concat(preprocess($(this)));//Concatenating all promises arrays
    });

    $.when.apply($,promises).then(function(){// Use $.when to execute a function when all deferreds are resolved.
        $("#pagemain").html(html);
    });
}

答案 1 :(得分:1)

Deferred's起初可能有点令人生畏,但是,像大多数事情一样,一旦灯泡继续运行并且你得到它,它就非常简单。创建延迟对象的简单设置如下:

var defer = $.Deferred(function(dfd) {
 // do the processing you need, and then...
 // when processing is complete, make a call to...
 dfd.resolve(/* return data goes here, if required */);
}).promise();

// use the deferred object like it was an ajax call
defer.then(/* do the stuff that needed to wait */);

所以,使用你的例子:

function setContent(html, url) {
  html = $.parseHTML(html);

  var defer = $.Deferred(function(dfd) {
    $(html).filter("form").each(function() {
      preprocess($(this));
    });

    dfd.resolve();
  }).promise();

  defer.then($("#pagemain").html(html));
}

答案 2 :(得分:0)

整洁的解决方案将在以下时间使用:

http://api.jquery.com/jQuery.when/

    $.when( {//your preprocessing function here
 } ).done(function( x ) {
      //your done action here
    });