完成所有操作后,动态链接jQuery $ .post()和触发调用事件. [英] Dynamically chain jQuery $.post() and fire call event after all are complete.

查看:236
本文介绍了完成所有操作后,动态链接jQuery $ .post()和触发调用事件.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列元素,一旦完成所有元素的保存",我想抓取,循环,验证,保存并继续到下一个元素,然后重定向用户.

I have a series of elements that I want to grab, loop, validate, save and continue to the next element, once all elements 'saves' are complete, then redirect the user.

元素的数量是动态的,并且通常可以快速保存.

The number of elements is dynamic, and genrally saves are fast.

$.each($('#wrapper').find('.question'), function(i, question) {
    var post_data = false;
    if(question) { 
        // validate based on type of question/expected data etc.... 
        // example data object
        post_data = {
            'question_id': question_id, 
            'question_text': question_text,
            // etc.... 
        };
        if(post_data) { 
            $.post('ajax_save_question', post_data)
            .done(function(data) { question.addClass('saved'); });
        }
    } else {
        // exit loop altogether
    }
}); 

// run after loop has finished and all questions have been saved.. 
window.location = 'display_results'; 

推荐答案

您可以使用$.when,您可以在其中传递任意数量的延迟. 完成所有操作后,将通过.then()附加的回调通知您. 请参见文档

You can use $.when, where you can pass in as many deferreds as you like. when all are done, you will be notified through the callback attached through .then() . See Documentation

var myFirstPost = $.post( ... ); 
var mySecondPost = $.post( ... );

$.when(myFirstPost, mySecondPost).then(function() {
    alert("all done");
});

在您的情况下,如果$.post在另一个函数调用中很深,则应将所有post调用保存到某个数组中.由于$.post始终返回Promise对象,因此您可以将其放入数组中.运行完所有循环后,使用$.when

In your case, where your $.post is quite deep in another function call, you should save all your post calls into some array. As $.post always returns a Promise Object, you can just put it into an array. After you have ran all your loop, use the $.when

// use apply, to pass in an array of promises
$.when.apply($, allMyPromisesArray).then( ... )

这篇关于完成所有操作后,动态链接jQuery $ .post()和触发调用事件.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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