edu*_*dev 2 javascript jquery jquery-callback
我需要mvFinishItUp()在满足两个条件时执行特定的功能.更具体地说,一个条件是另一个条件的回调成功$.ajax是代码的正常流程,直到它到达函数.有点这样:
$.ajax({
url: mv_finalUrl,
success: function (data) {
mvFinishItUp(data);
},
dataType: 'html'
});
/* here a lot more code, with animations and some delays */
mvFinishItUp(data) {
/* My function code */
/* But this code must only run after it has been called via the call back
and after all the other code has been ran as well */
}
Run Code Online (Sandbox Code Playgroud)
因此,如果ajax回调更快,或者相反,函数必须等待所有代码.有关如何实施这一点的任何想法?
我愿意改变脚本代码的整个概念,因为我相信ajax和函数本身之间的松散代码应该转到函数中...
这是jQuery Deferred对象的完美用例.
success:从AJAX调用中删除参数,稍后注册处理程序:
var jqxhr = $.ajax(...);
// do some other synchronous stuff
...
// and *then* register the callback
jqxhr.done(mvFinishItUp);
Run Code Online (Sandbox Code Playgroud)
延迟对象在该事件已经完成后在AJAX事件上注册时(通过设计)非常好地应对.