Ajax请求会产生若干不同的事件,我们可以订阅这些事件并在其中处理我们的逻辑。在jQuery这里有两种Ajax事件:局部事件 和 全局事件。
局部事件就是在每次的Ajax请求时在方法内定义的,例如:
$.ajax({
beforeSend: function(){
// Handle the beforeSend event
},
complete: function(){
// Handle the complete event
}
// ...
});
全局事件是每次的Ajax请求都会触发的,它会向DOM中的所有元素广播,在上面 getScript() 示例中加载的脚本就是全局Ajax事件。全局事件可以如下定义:
$("#loading").bind("ajaxSend", function(){
$(this).show();
}).bind("ajaxComplete", function(){
$(this).hide();
});
或者:
$("#loading").ajaxStart(function(){
$(this).show();
});
我们可以在特定的请求将全局事件禁用,只要设置下 global 选项就可以了:
$.ajax({
url: "test.html",
global: false,// 禁用全局Ajax事件.
// ...
});
下面是jQuery官方给出的完整的Ajax事件列表:
· ajaxStart(Global Event)
This event is broadcast if an Ajax request is started and no other Ajax requests are currently running.
· 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(Global Event)
This global event is also triggered before the request is run.
· success(Local Event)
This event is only called if the request was successful (no errors from the server, no errors with the data).
· ajaxSuccess(Global Event)
This event is also only called if the request was successful.
· 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(Global Event)
This global event behaves the same as the local error event.
· 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(Global Event)
This event behaves the same as the complete event and will be triggered every time an Ajax request finishes.
· ajaxStop(Global Event)
This global event is triggered if there are no more Ajax requests being processed.
具体的全局事件请参考API文档。
好了,下面开始说jQuery里面功能最强的Ajax请求方法 $.ajax();