[英]Wait unitl ajax and its callback function finish
I am building a web app that allows users to perform a number of actions simultaneously. 我正在构建一个Web应用程序,该应用程序允许用户同时执行许多操作。 For example, user can open a list, delete a list, or add a new list. 例如,用户可以打开列表,删除列表或添加新列表。
Each action makes an ajax call and executes a callback function to update UI upon success. 每个操作都会进行ajax调用,并执行回调函数以在成功后更新UI。 I want to make sure these actions are performed in a serialized manner, so that the UI does not go out of sync. 我想确保以串行方式执行这些操作,以使UI不会不同步。 For example, if user opens a list, but deletes the list a fraction of a second later, depending on which ajax call finsihes first, it may display the list which is supposed to be now deleted. 例如,如果用户打开一个列表,但是在一秒钟之内删除列表,这取决于首先执行哪个ajax调用,则它可能会显示应该立即删除的列表。
To accomplish this, for each action, I want to wait until an ajax call and its callback function are finished. 要做到这一点,每一个动作,我想等到一个Ajax调用及其回调函数完成。 How can I achieve this? 我该如何实现?
With Jquery, you could add async: false
to your Ajax call or use Jquery deferred to make sure an action is only issued after the Ajax calls are finished (assuming you use Jquery). 使用Jquery时,您可以在Ajax调用中添加async: false
或使用Jquery deferred来确保仅在Ajax调用完成后才发出操作(假设您使用Jquery)。
If you have multiple Ajax requests, an example could look like: 如果您有多个Ajax请求,则示例如下所示:
$.ajax({url: url}).pipe(function() {
// some ajax stuff
return $.ajax({});
}).pipe(function() {
// some more ajax stuff (3rd request)
return $.ajax({});
}).done(function() {
// done with all ajax requests...
});
If you're using jQuery the .always()
callback is called after .done()
/ .fail()
. 如果您使用的是jQuery, .always()
在.done()
/ .fail()
之后调用.always()
回调。
$.ajax("example.php")
.done(function() {
alert("success");
})
.fail(function() {
alert("error");
})
.always(function() {
alert("complete"); //Called after done/fail callbacks
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.