当global: true时。在Ajax请求生命周期内,以下这些事件将被触发。
ajaxStart (global):如果没有其他Ajax请求当前活跃将会被触发。
ajaxBeforeSend (data: xhr, options):再发送请求前,可以被取消。
ajaxSend (data: xhr, options):像 ajaxBeforeSend,但不能取消。
ajaxSuccess (data: xhr, options, data):当返回成功时。
ajaxError (data: xhr, options, error):当有错误时。
ajaxComplete (data: xhr, options):请求已经完成后,无论请求是成功或者失败。
ajaxStop (global):如果这是最后一个活跃着的Ajax请求,将会被触发。
默认情况下,Ajax事件在document对象上触发。然而,如果请求的 context 是一个DOM节点,该事件会在此节点上触发然后再DOM中冒泡。唯一的例外是 ajaxStart & ajaxStop这两个全局事件。
$(document).on('ajaxBeforeSend', function(e, xhr, options){
// This gets fired for every Ajax request performed on the page.
// The xhr object and $.ajax() options are available for editing.
// Return false to cancel this request.
})
$.ajax({
type: 'GET',
url: '/projects',
// data to be added to query string:
data: { name: 'Zepto.js' },
// type of data we are expecting in return:
dataType: 'json',
timeout: 300,
context: $('body'),
success: function(data){
// Supposing this JSON payload was received:
// {"project": {"id": 42, "html": "
// append the HTML to context object.
this.append(data.project.html)
},
error: function(xhr, type){
alert('Ajax error!')
}
})
// post a JSON payload:
$.ajax({
type: 'POST',
url: '/projects',
// post payload:
data: JSON.stringify({ name: 'Zepto.js' }),
contentType: 'application/json'
})