我似乎找不到关于这个和 the documentation 的明确答案没有说清楚。
从我的理解,以及从什么other answers已经提到,全局 ajaxComplete
事件发生在全局 ajaxSuccess
或 ajaxError
事件之后。
也就是说,这两组事件之间的时间关系是什么?
ajaxComplete
是否保证在ajaxSuccess
/ajaxError
启动后启动?ajaxComplete
是否保证在ajaxSuccess
/ajaxError
完成后启动?- 没有保证?
作为背景知识,我试图确保我的 ajaxComplete
处理程序在 ajaxSuccess
/ajaxError
之后才运行处理程序完成。
最佳答案
ajaxComplete
在ajaxSuccess
/ajaxError
处理程序完成 之后触发。
这是 jQuery 2.1.4 中的相关代码(在 jQuery 1.11.3 中也相同):
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger("ajaxStop");
}
}
为了验证这一点,我设置了一个实验,可以任意指定 ajaxSuccess
处理程序需要多长时间才能完成。
$(document).ajaxSuccess(function (e, xhr, settings) {
var startTime = (new Date()).getTime();
// Intentionally waste an arbitrary length of time
while ( (new Date()).getTime() - startTime < 1000 ) { }
var endTime = (new Date()).getTime();
console.log('ajaxSuccess\n'
+ ' Start: ' + startTime + '\n'
+ ' End: ' + endTime
);
});
$(document).ajaxComplete(function (e, xhr, settings) {
var startTime = (new Date()).getTime();
console.log('ajaxComplete\n'
+ ' Start: ' + startTime
);
});
$.get('/');
该实验证实了我之前观察到的情况,即 ajaxSuccess
/ajaxError
总是在 ajaxComplete
开始之前完成,无论它持续多长时间拿走了。
关于javascript - ajaxSuccess/ajaxError 与 ajaxComplete 的 jQuery 计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30127244/