我使用jQuery而且我不想在我的应用程序上并发AJAX调用,每次调用必须等待之前的开始。如何实现?有帮手吗?
UPDATE如果有任何同步版本的XMLHttpRequest或jQuery.post我想知道。但是顺序!=同步,我想要一个异步和顺序的解决方案。
解决方法
使用同步ajax调用有一个更好的方法。 Jquery ajax返回一个延迟,所以你可以使用管道链接来确保每个ajax调用在下一次运行之前完成。这里有一个更加深入的例子,你可以在
play with on jsfiddle工作的例子。
// How to force async functions to execute sequentially // by using deferred pipe chaining. // The master deferred. var dfd = $.Deferred(),// Master deferred dfdNext = dfd; // Next deferred in the chain x = 0,// Loop index values = [],// Simulates $.ajax,but with predictable behavIoUr. // You only need to understand that higher 'value' param // will finish earlier. simulateAjax = function (value) { var dfdAjax = $.Deferred(); setTimeout( function () { dfdAjax.resolve(value); },1000 - (value * 100) ); return dfdAjax.promise(); },// This would be a user function that makes an ajax request. // In normal code you'd be using $.ajax instead of simulateAjax. requestAjax = function (value) { return simulateAjax(value); }; // Start the pipe chain. You should be able to do // this anywhere in the program,even // at the end,and it should still give the same results. dfd.resolve(); // Deferred pipe chaining. // What you want to note here is that an new // ajax call will not start until the prevIoUs // ajax call is completely finished. for (x = 1; x <= 4; x++) { values.push(x); dfdNext = dfdNext.pipe(function () { var value = values.shift(); return requestAjax(value). done(function(response) { // Process the response here. }); }); }
有些人评论说,他们不知道代码的作用。为了理解它,您首先需要了解JavaScript承诺。我很肯定,承诺很快就会成为一个本地的JavaScript语言功能,所以应该给你很好的学习动机。