在完成所有操作后,动态链接jQuery $ .post()和fire call事件。

我有一系列元素,我想抓取,循环,validation,保存并继续下一个元素,一旦所有元素“保存”完成,然后重定向用户。

元素的数量是动态的,并且节省的速度很快。

$.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()附加的回调通知您。 见文档

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

在你的情况下,你的$.post在另一个函数调用中非常深,你应该将所有的post调用保存到某个数组中。 由于$.post总是返回一个Promise对象,你可以把它放到一个数组中。 运行完所有循环后,使用$.when

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

您可能还想查看$ .ajaxStop事件。 它会监听一系列ajax请求中的最后一个请求何时完成:

 $(function() { $( document ).ajaxStop( function() { //all done -- you can now redirect to the next page }); }); 

您现有的代码保持不变。

 $(function() { var arr = $.makeArray($("#wrapper").find(".question")); $.when(arr) .then(function(elem) { $.each(elem, function(index, value) { var post_data = { "question_id" : $(value).attr("id"), "question_text" : $(value).text() }; if (post_data) { var settings = function (_post_data) { return { url: "/echo/json/", type: "POST", async: true, data: { json: JSON.stringify(_post_data) } } }; $.ajax(settings(post_data)) .done(function(data, textStatus, jqxhr) { console.log(data); $(value).addClass("saved"); }) } else { return false } }); return [ elem, $(document) ] }) .always(function(data) { data[1].on("ajaxStop", function(e) { $("body").append(data[0].length + " items completed, done at " + $.now()); // `complete` `callback`, ieg, // run after loop has finished and all questions have been saved.. // window.location = "display_results"; }); }); }); 

jsfiddle http://jsfiddle.net/guest271314/GGhq5/