1

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

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

我努力了

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

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

4

1 回答 1

1

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

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
});
于 2013-04-06T10:45:59.597 回答