javascript - 如何在每个ajax调用上绑定(bind)开始和完成事件

标签 javascript ajax

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

我有一个应用程序,我需要知道通过接口(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/

相关文章:

javascript - 使用jquery ajax调用nodejs获取json数据

Javascript AJAX 登录弹出窗口

javascript - 将 ajax Promise 与 $.when().done 一起使用

javascript - FormData 从 multipart/form-data 更改为 form-urlencoded?

javascript - 多个数据字段的 jQuery DataTables 列定义

javascript - 如何按 MongoDB 文档中的字段对数组进行排序

javascript - 使用 http post 请求传递有关事件更改的参数

javascript - AngularJS中路由逻辑的延迟启动

javascript - 如果服务器响应 401/402 状态,Deferred.fail() 会被触发吗?

javascript - 如何在不刷新页面的情况下更改路由和内容? (机器人友好)