我的问题可能非常基本,但我已经坚持了很长一段时间了。
我有一个应用程序,我需要知道通过接口(interface)进行的任何 ajax 调用的开始或完成,无论它是 YAHOO.util.connect.asyncRequest 还是 jquery 的 $.ajax() 或简单的 XMLHttpRequest。
我已经尝试过
$(document).ajaxComplete(function() {
$( ".log" ).text( "Triggered ajaxComplete handler." );
})
但我认为它只绑定(bind) jquery ajax 函数触发的事件
最佳答案
喜欢这个答案Add a "hook" to all AJAX requests on a page您可以查看该代码并尝试一下。
每个 ajax 调用(不仅是 jQuery)中的 javascript 代码钩子(Hook)让您定义自己的处理程序。
function addXMLRequestCallback(callback){
var oldSend, i;
if( XMLHttpRequest.callbacks ) {
// we've already overridden send() so just add the callback
XMLHttpRequest.callbacks.push( callback );
} else {
// create a callback queue
XMLHttpRequest.callbacks = [callback];
// store the native send()
oldSend = XMLHttpRequest.prototype.send;
// override the native send()
XMLHttpRequest.prototype.send = function(){
// process the callback queue
// the xhr instance is passed into each callback but seems pretty useless
// you can't tell what its destination is or call abort() without an error
// so only really good for logging that a request has happened
// I could be wrong, I hope so...
// EDIT: I suppose you could override the onreadystatechange handler though
for( i = 0; i < XMLHttpRequest.callbacks.length; i++ ) {
XMLHttpRequest.callbacks[i]( this );
}
// call the native send()
oldSend.apply(this, arguments);
}
}
}
// e.g.
addXMLRequestCallback( function( xhr ) {
console.log( xhr.responseText ); // (an empty string)
});
addXMLRequestCallback( function( xhr ) {
console.dir( xhr ); // have a look if there is anything useful here
});
关于javascript - 如何在每个ajax调用上绑定(bind)开始和完成事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15849698/