如何在每个ajax调用上绑定start和complete事件

时间:2013-04-06 10:22:32

标签: javascript ajax

我的问题可能非常基本,但我现在已经坚持了很长时间。

我有一个应用程序,我需要知道通过接口进行的任何ajax调用的开始或完成,无论是YAHOO.util.connect.asyncRequest还是$ .ajax()的jquery或简单的XMLHttpRequest。

我试过了

$(document).ajaxComplete(function() {
$( ".log" ).text( "Triggered ajaxComplete handler." );
})

但我认为它只绑定来自jquery ajax函数的事件触发

1 个答案:

答案 0 :(得分:0)

喜欢这个答案Add a "hook" to all AJAX requests on a page,您可以查看该代码并尝试一下。

javascript中的代码挂钩每次ajax调用(不仅仅是jQuery),让你定义自己的处理程序。

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
});