jQuery - AJAX Events

创建时间:
2018-08-26 23:35
最近更新:
2018-09-04 15:34

Documentation

Ajax Events
Ajax requests produce a number of different events that you can subscribe to.
Here's a full list of the events and in what order they are broadcast.
There are two types of events: Local Events and Global Events.

Global Ajax Event Handlers

jQuery 的 AJAX 事件流

成功时 (8个事件)

  1. ajaxStart
  2. beforeSend
  3. ajaxSend
  4. success
  5. ajaxSuccess
  6. complete
  7. ajaxComplete
  8. ajaxStop

失败时 (8个事件)

  1. ajaxStart
  2. beforeSend
  3. ajaxSend
  4. error
  5. ajaxError
  6. complete
  7. ajaxComplete
  8. ajaxStop

Summary: GlobalEvent * 6 + LocalEvent * 4 = 10

Global Ajax Event Handlers 全局事件

Global Ajax Event Handlers
这些方法注册处理程序,当某些事件比如初始化或完成时被调用,为页面上任何AJAX请求触发。
These methods register handlers to be called when certain events, such as initialization or completion, take place for any AJAX request on the page.
如果jQuery.ajaxSetup()的global属性为true(默认),这些全局事件被每个AJAX请求触发。
The global events are fired on each AJAX request if the global property in jQuery.ajaxSetup() is true, which it is by default.
Note: Global events are never fired for cross-domain script or JSONP requests, regardless of the value of global.

每次Ajax请求都会触发的事件,它会向DOM中的所有元素广播。
These events are broadcast to all elements in the DOM, triggering any handlers which may be listening. You can listen for these events like so:

$("#loading")
.bind("ajaxSend",function(){
    $(this).show();
})
.bind("ajaxComplete",function(){
    $(this).hide();
});

or:

$("#loading").ajaxStart(function(){
    $(this).show();
});

以上示例演示了为 AJAX 全局事件绑定处理程序的 2 种途径: 通过 .bind() 或直接绑定。

在 jQuery.ajaxSetup(options) 中的 options 参数属性中,有一个 global 属性 (type:bool; default:true)
这个属性用来设置是否触发全局的Ajax事件。
可以通过将默认options的global属性设置为false来取消全局Ajax事件的触发。
我们可以在特定的请求将全局事件禁用,只要设置下global选项就可以了:
Global events can be disabled, for a particular Ajax request, by passing in the global option, like so:

$.ajax({
    url:"test.html",
    global:false,
    //...
});

共 6 种全局事件

按触发次序排列:

  1. ajaxStart
  2. ajaxSend
  3. ajaxSuccess
  4. ajaxError
  5. ajaxComplete
  6. ajaxStop

jQuery中ajax全局事件的应用

大家看到这个题目的时候可能有点糊涂,AJAX 还有事件? 答案是否定的。
只是 jQuery 为了控制 AJAX 的流程,比如停止,监听当前的状态等等而自己定义的事件,
这个事件说简单点就是自定义函数。

jQuery 共定义了以下 6 个事件:

  1. ajaxStart
  2. ajaxSend
  3. ajaxSuccess
  4. ajaxComplete
  5. ajaxStop
  6. ajaxError

下面逐一介绍:

ajaxStart
在调用Ajax的时候首先就会触发该事件,Ajax计数器加1,不传递任何参数。
源码:jQuery.event.trigger("ajaxStart");

ajaxSend
执行beforeSend之后,XMLHttpRequest调用send之前,触发该事件,传递包含两个元素的数组对象,第一个元素是当前的XMLHttpRequest对象,第二个元素是当前Ajax的属性对象,这个可以参考前边的ajax参数列表。
源码:jQuery.event.trigger("ajaxSend",[xhr,s]);

ajaxSuccess
Ajax执行到success最后的时候,触发该事件,传递的参数与上述ajaxSend相同。
源码:jQuery.event.trigger("ajaxSuccess",[xhr,s]);

ajaxComplete
Ajax执行complete后、触发ajaxStop前,触发该事件,传递的参数与上述ajaxSend相同。
源码jQuery.event.trigger("ajaxComplete",[xhr,s]);//xhr就是当前的XMLHttpRequest对象,s就是Ajax的属性对象

ajaxStop
Ajax执行到complete最后的时候触发该事件,Ajax计数器减1,不传递任何参数。
源码:jQuery.event.trigger("ajaxStop")

ajaxError
捕获到XMLHttpRequest异常时,触发该事件,传递的参数数组比上述ajaxSend多一个元素:错误代码。
源码:jQuery.event.trigger("ajaxError",[xhr,s,e]);

Example:

$("body").ajaxStart(function(){alert("ajaxStart()执行!你可以在这里显示Loading...");});
$("body").ajaxSend(function(){alert("ajaxSend()执行!");});
$("body").ajaxSuccess(function(){alert("ajaxSuccess()执行!");});
$("body").ajaxComplete(function(){alert("ajaxComplete()执行!");});
$("body").ajaxStop(function(){alert("ajaxStop()执行!你可以在这里隐藏Loading...");});
$("body").ajaxError(function(){alert("ajaxError()执行!");});

Example:
一个页面上有三个 AJAX 请求 (都是异步请求),但是需求是不能锁住浏览器还要 AJAX 顺序执行,
意思就是第一个 AJAX 执行完成之后才执行第二个,再执行第三个,
如果有一个异常,其他的 AJAX 也不需要请求,
这样的情况的时候这些事件就派上用场了。

var AjaxStack=[]; //AJAX 等待执行队列 (先进先出)

$(document).ajaxSuccess(function(o, s){
    AjaxStack.shift();
});

$(document).ajaxComplete(function(){
    var tmp=AjaxStack.shift();
    if(tmp){
        $(tmp[0]).loading(tmp[1], tmp[2], tmp[3]);
    }
});

$.fn.loading function(u,opt,f) {
    AjaxStack.push([this, u, opt, f]);
    if($.active){
        return;
    }
    $.ajax({
        data: opt,
        type: "get",
        url: u,
        beforeSend: function(XMLHttpRequest){
            //加一些效果测试是不是顺序执行的
        },
        success: function(data,textStatus){
            //sucuss
        },
        complete: function(XMLHttpRequest,textStatus){
            //complete
        }
    });
};

$(‘#test1’).loading(‘test1.html’);
$(‘#test2’).loading(‘test2.html’);
$(‘#test3’).loading(‘test3.html’);

注意,在 AJAX 全部事件申明的时候,也是 jQuery 对象,但是该对象不起任何作用,只是为了能访问到,所以说 $(document).ajaxComplete(function(){})$(‘#test1’).ajaxComplete(function(){}) 是等价的。为了命名规范你可以定义成和 AJAX 调用的对象是一致,但是没有任何实际意义,从触发的源码中应该看出,他用的是全局对象 jQuery。

Local Events 局部事件

在 AJAX 请求的方法内定义的事件。
These are callbacks that you can subscribe to within the Ajax request object, like so:

$.ajax({
    beforeSend:function(){
        //Handle the beforeSend event
    },
    complete:function(){
        //Handle the complete event
    }
    //......
});

共 4 种局部事件

按触发次序排列:

  1. beforeSend
  2. success
  3. error
  4. complete

Events List

This is the full list of Ajax events that are broadcast, and in the order in which they are broadcast.
The indented events are broadcast for each and every Ajax request (unless a global option has been set).
The ajaxStart and ajaxStop events are events that relate to all Ajax requests together.

.ajaxStart(handler()) (Global Event)

version added: 1.0
Returns: jQuery
Description: Register a handler to be called when the first Ajax request begins. This is an Ajax Event. This event is broadcast if an Ajax request is started and no other Ajax requests are currently running.
handler(): The function to be invoked.

无论何时一个AJAX请求即将被发送,jQuery检查是否有任何其它未解决的AJAX请求。
Whenever an Ajax request is about to be sent, jQuery checks whether there are any other outstanding Ajax requests.
如果没有进行中的AJAX请求,jQuery触发ajaxStart事件,在此时任何已注册的ajaxStart事件处理程序被执行。
If none are in progress, jQuery triggers the ajaxStart event. Any and all handlers that have been registered with the .ajaxStart() method are executed at this time.

//To observe this method in action, we can set up a basic Ajax load request:
$(function(){
    $(document.body).html(
        '<input type="button" value="Trigger $.load()."/>' +
        '<p>Placeholder for $.ajaxStar() message.</p>' +
        '<div>Placeholder for $.load() HTML fragment.</div>'
    );
    //We can attach our event handler to any element:
    //Note: Because .ajaxStart() is implemented as a method of jQuery object instances, we can use the this keyword as we do here to refer to the selected elements within the callback function.
    $("p").ajaxStart(function(){
        $(this).text("From JqueryObject.ajaxStart().");
        alert(this.innerHTML);
    });
    //Now, we can make an Ajax request using any jQuery method:
    $("input").click(function(){
        $("div").load(
//              "JsCssTester1.htm",
            "JsCssTester1.htm #Div0",
            function(){
                alert("From JqueryObject.load() complete callback method.");
            });
//          $("div").load("http://www.abc.com/");//无反应,因为same origin policy
//          $("div").load("http://www.abc.com/Article/ArticleList.aspx");//无反应,因为same origin policy
//          $("div").load("http://www.abc.com/Article/ArticleList.aspx div.LinkBlack.UnderlineNone");//无反应,因为same origin policy
    });
});
//When the user clicks the button and the Ajax request is sent, the message is displayed.

Example:
Show a loading message whenever an Ajax request starts (and none is already active).

$("#loading").ajaxStart(function(){$(this).show();});

beforeSend (Local Event)

This event, which is triggered before an Ajax request is started, allows you to modify the XMLHttpRequest object (setting additional headers, if need be.)

.ajaxSend(handler(event,jqXHR,ajaxOptions)) (Global Event)

version added: 1.0
Returns: jQuery
Description: Attach a function to be executed before an Ajax request is sent. This is an Ajax Event. This global event is also triggered before the request is run.
handler(event,jqXHR,ajaxOptions): The function to be invoked.

Whenever an Ajax request is about to be sent, jQuery triggers the ajaxSend event. Any and all handlers that have been registered with the .ajaxSend() method are executed at this time.

//To observe this method in action, we can set up a basic Ajax load request:
$(function(){
    $(document.body).html(
        '<input type="button" value="Trigger $.load()."/>' +
        '<p>Placeholder for $.ajaxStar() message.</p>' +
        '<div>Placeholder for $.load() HTML fragment.</div>'
    );
    //We can attach our event handler to any element:
    //Note: Because .ajaxSend() is implemented as a method of jQuery object instances, we can use the this keyword as we do here to refer to the selected elements within the callback function.
    $("p").ajaxSend(function(){
        $(this).text("From JqueryObject.ajaxSend().");
        alert(this.innerHTML);
    });
    //Now, we can make an Ajax request using any jQuery method:
    $("input").click(function(){
        $("div").load(
//          "JsCssTester1.htm",
            "JsCssTester1.htm #Div0",
            function(){
                alert("From JqueryObject.load() complete callback method.");
            });
//          $("div").load("http://www.abc.com/");//无反应,因为same origin policy
//          $("div").load("http://www.abc.com/Article/ArticleList.aspx");//无反应,因为same origin policy
//          $("div").load("http://www.abc.com/Article/ArticleList.aspx div.LinkBlack.UnderlineNone");//无反应,因为same origin policy
    });
});
//When the user clicks the button and the Ajax request is about to begin, the message is displayed.

不管什么 AJAX 请求被发送,所有.ajaxSend()事件处理程序被调用。
All ajaxSend handlers are invoked, regardless of what Ajax request is to be sent.
If we must differentiate between the requests, we can use the parameters passed to the handler. Each time an ajaxSend handler is executed, it is passed the event object, the jqXHR object (in version 1.4, XMLHttpRequestobject), and the settings object that was used in the creation of the Ajax request. For example, we can restrict our callback to only handling events dealing with a particular URL:

$('.log').ajaxSend(function(event,jqXHR,ajaxOptions) {
    if (ajaxOptions.url == 'ajax/test.html') {
        $(this).text('Triggered ajaxSend handler.');
    }
});

Example: Show a message before an Ajax request is sent.

$("#msg").ajaxSend(function(event,jqXHR,ajaxOptions){
    $(this).append("<li>Starting request at"+settings.url+"</li>");
});

success (Local Event)

This event is only called if the request was successful (no errors from the server, no errors with the data).

.ajaxSuccess(handler(event,XMLHttpRequest,ajaxOptions)) (Global Event)

version added: 1.0
Returns: jQuery
Description: Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event. This event is also only called if the request was successful.
handler(event,XMLHttpRequest,ajaxOptions): The function to be invoked.

Whenever an Ajax request completes successfully, jQuery triggers the ajaxSuccess event. Any and all handlers that have been registered with the .ajaxSuccess() method are executed at this time.

//To observe this method in action, we can set up a basic Ajax load request:
$(function(){
    $(document.body).html(
        '<input type="button" value="Trigger $.load()."/>' +
        '<p>Placeholder for $.ajaxStar() message.</p>' +
        '<div>Placeholder for $.load() HTML fragment.</div>'
    );
    //We can attach our event handler to any element:
    //Note: Because .ajaxSuccess() is implemented as a method of jQuery object instances, we can use the this keyword as we do here to refer to the selected elements within the callback function.
    $("p").ajaxSuccess(function(){
        $(this).text("From JqueryObject.ajaxSuccess().");
        alert(this.innerHTML);
    });
    //Now, we can make an Ajax request using any jQuery method:
    $("input").click(function(){
        $("div").load(
//          "JsCssTester1.htm",
            "JsCssTester1.htm #Div0",
            function(){
                alert("From JqueryObject.load() complete callback method.");
            });
//          $("div").load("http://www.abc.com/");//无反应,因为same origin policy
//          $("div").load("http://www.abc.com/Article/ArticleList.aspx");//无反应,因为same origin policy
//          $("div").load("http://www.abc.com/Article/ArticleList.aspx div.LinkBlack.UnderlineNone");//无反应,因为same origin policy
    });
});
//When the user clicks the button and the Ajax request completes successfully, the message is displayed.

All ajaxSuccess handlers are invoked, regardless of what Ajax request was completed. If we must differentiate between the requests, we can use the parameters passed to the handler.
Each time an ajaxSuccess handler is executed, it is passed the event object, the XMLHttpRequest object, and the settings object that was used in the creation of the request. For example, we can restrict our callback to only handling events dealing with a particular URL:

$('.log').ajaxSuccess(function(event,XMLHttpRequest,ajaxOptions) {
    if (ajaxOptions.url == 'ajax/test.html') {
    $(this).text('Triggered ajaxSuccess handler. The ajax response was:'+xhr.responseText );
    }
});

Note: You can get the returned ajax contents by looking at xhr.responseXML or xhr.responseText for xml and html respectively.

Example: Show a message when an Ajax request completes successfully.

$("#msg").ajaxSuccess(function(event,XMLHttpRequest,ajaxOptions){
    $(this).append("<li>Successful Request!</li>");
});

error (Local Event)

This event is only called if an error occurred with the request (you can never have both an error and a success callback with a request).

.ajaxError(handler(event,jqXHR,ajaxSettings,thrownError)) (Global Event)

version added: 1.0
Returns: jQuery
Description: Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event. This global event behaves the same as the local error event.
handler(event,jqXHR,ajaxSettings,thrownError): The function to be invoked.

Whenever an Ajax request completes with an error, jQuery triggers the ajaxError event. Any and all handlers that have been registered with the .ajaxError() method are executed at this time.

//To observe this method in action, we can set up a basic Ajax load request:
$(function(){
    $(document.body).html(
        '<input type="button" value="Trigger $.load()."/>' +
        '<p>Placeholder for $.ajaxStar() message.</p>' +
        '<div>Placeholder for $.load() HTML fragment.</div>'
    );
    //We can attach our event handler to any element:
    //Note: Because .ajaxError() is implemented as a method of jQuery object instances, we can use the this keyword as we do here to refer to the selected elements within the callback function.
    $("p").ajaxError(function(){
        $(this).text("From JqueryObject.ajaxError().");
        alert(this.innerHTML);
    });
    //Now, we can make an Ajax request using any jQuery method:
    $("input").click(function(){
        $("div").load(
            "missing.htm",
            function(){
                alert("From JqueryObject.load() complete callback method.");
            });
    });
});
//When the user clicks the button and the Ajax request fails, because the requested file is missing, the message is displayed.

All ajaxError handlers are invoked, regardless of what Ajax request was completed. To differentiate between the requests, you can use the parameters passed to the handler. Each time an ajaxError handler is executed, it is passed the event object, the jqXHR object (prior to jQuery 1.5, the XHR object), and the settings object that was used in the creation of the request. If the request failed because JavaScript raised an exception, the exception object is passed to the handler as a fourth parameter. For example, to restrict the error callback to only handling events dealing with a particular URL:

$( "div.log" ).ajaxError(function(event,jqXHR,ajaxSettings,thrownError){
    if ( ajaxSettings.url == "ajax/missing.html" ) {
        $(this).text( "Triggered ajaxError handler." );
    }
});

Example: Show a message when an Ajax request fails.

$("#msg").ajaxError(function(event,jqXHR,ajaxSettings,thrownError){
    $(this).append("<li>Error requesting page " + settings.url + "</li>");
});

complete (Local Event)

This event is called regardless of if the request was successful, or not. You will always receive a complete callback, even for synchronous requests.

.ajaxComplete(handler(event,XMLHttpRequest,ajaxOptions)) (Global Event)

version added: 1.0
Returns: jQuery
Description: Register a handler to be called when Ajax requests complete. This is an Ajax Event. This event behaves the same as the complete event and will be triggered every time an Ajax request finishes.
handler(event,XMLHttpRequest,ajaxOptions): The function to be invoked.

Whenever an Ajax request completes, jQuery triggers the ajaxComplete event. Any and all handlers that have been registered with the .ajaxComplete() method are executed at this time.

//To observe this method in action, we can set up a basic Ajax load request:
$(function(){
    $(document.body).html(
        '<input type="button" value="Trigger $.load()."/>' +
        '<p>Placeholder for $.ajaxStar() message.</p>' +
        '<div>Placeholder for $.load() HTML fragment.</div>'
    );
    //We can attach our event handler to any element:
    //Note: Because .ajaxComplete() is implemented as a method of jQuery object instances, we can use the this keyword as we do here to refer to the selected elements within the callback function.
    $("p").ajaxComplete(function(){
        $(this).text("From JqueryObject.ajaxComplete().");
        alert(this.innerHTML);
    });
    //Now, we can make an Ajax request using any jQuery method:
    $("input").click(function(){
        $("div").load(
//          "JsCssTester1.htm",
            "JsCssTester1.htm #Div0",
            function(){
                alert("From JqueryObject.load() complete callback method.");
            });
//          $("div").load("http://www.abc.com/");//无反应,因为same origin policy
//          $("div").load("http://www.abc.com/Article/ArticleList.aspx");//无反应,因为same origin policy
//          $("div").load("http://www.abc.com/Article/ArticleList.aspx div.LinkBlack.UnderlineNone");//无反应,因为same origin policy
    });
});
//When the user clicks the button and the Ajax request completes, the message is displayed.

All ajaxComplete handlers are invoked, regardless of what Ajax request was completed. If we must differentiate between the requests, we can use the parameters passed to the handler.
Each time an ajaxComplete handler is executed, it is passed the event object, the XMLHttpRequest object, and the settings object that was used in the creation of the request. For example, we can restrict our callback to only handling events dealing with a particular URL:

$('.log').ajaxComplete(function(e, xhr, settings) {
    if (settings.url == 'ajax/test.html') {
        $(this).text('Triggered ajaxComplete handler. The result is '+xhr.responseHTML);
    }
});

Note: You can get the returned ajax contents by looking at xhr.responseXML or xhr.responseHTML for xml and html respectively.

Example: Show a message when an Ajax request completes.

$("#msg").ajaxComplete(function(event,request,settings){
    $(this).append("<li>Request Complete.</li>");
});

.ajaxStop(handler()) (Global Event)

version added: 1.0
Returns: jQuery
Description: Register a handler to be called when all Ajax requests have completed. This is an Ajax Event. This global event is triggered if there are no more Ajax requests being processed.
handler(): The function to be invoked.

Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests. If none remain, jQuery triggers the ajaxStop event. Any and all handlers that have been registered with the .ajaxStop() method are executed at this time. The ajaxStop event is also triggered if the last outstanding Ajax request is cancelled by returning false within the beforeSend callback function.

//To observe this method in action, we can set up a basic Ajax load request:
$(function(){
    $(document.body).html(
        '<input type="button" value="Trigger $.load()."/>' +
        '<p>Placeholder for $.ajaxStar() message.</p>' +
        '<div>Placeholder for $.load() HTML fragment.</div>'
    );
    //We can attach our event handler to any element:
    //Note: Because .ajaxStop() is implemented as a method of jQuery object instances, we can use the this keyword as we do here to refer to the selected elements within the 
callback function.
    $("p").ajaxStop(function(){
        $(this).text("From JqueryObject.ajaxStop().");
        alert(this.innerHTML);
    });
    //Now, we can make an Ajax request using any jQuery method:
    $("input").click(function(){
        $("div").load(
//          "JsCssTester1.htm",
            "JsCssTester1.htm #Div0",
            function(){
                alert("From JqueryObject.load() complete callback method.");
            });
//          $("div").load("http://www.abc.com/");//无反应,因为same origin policy
//          $("div").load("http://www.abc.com/Article/ArticleList.aspx");//无反应,因为same origin policy
//          $("div").load("http://www.abc.com/Article/ArticleList.aspx div.LinkBlack.UnderlineNone");//无反应,因为same origin policy
    });
});
//When the user clicks the button and the Ajax request completes, the message is displayed.

Example: Hide a loading message after all the Ajax requests have stopped.

$("#loading").ajaxStop(function(){$(this).hide();});