繁体   English   中英

如何在每个ajax调用上绑定开始和完成事件

[英]How to bind start and complete event on every ajax call

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

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

我努力了

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

但我认为它只绑定从jQuery Ajax函数触发的事件

像这个答案一样,在页面上的所有AJAX请求中添加一个“钩子”,您可以查看该代码并进行尝试。

该代码在每个ajax调用中(不仅是jQuery)都钩在javascript中,并允许您定义自己的处理程序。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM