1. ajaxStart和ajaxStop
$(document).ajaxStart(function () {
$(".loading").show(); //发送请求前执行。
})
$(document).ajaxStop(function () {
$(".loading").hide(); //接收结束后执行。
})
2. 设置timeout
$.ajax({timeout: 500}); //单位是毫秒$
3. 设置global
$.ajax({global: false}); //不触发全局,比如ajaxStart和ajaxStop
4. 错误处理
$.ajax({
error: function(xhr, errorText, errorType) {
console.log(xhr, errorText, errorType);
},
beforeSend: function () {
},
complete: function () {
},
success: function () {
}
});
$.post("user1.php").error(function (xhr, status, info) {
console.log(xhr, status, info);
});
5. 全局错误处理
$(document).ajaxError(function (event, xhr, settings, errorType) {
//
})
6. 其他全局处理函数
$("form input[type=button]").click(function () {
$.post("user.php", $("form").serialize()).success(function () {
//局部成功处理函数
});
});
$(document).ajaxSend(function (event, xhr, settings) {
alert("before send");
});
$(document).ajaxComplete(function (event, xhr, settings) {
alert("send complete");
});
$(document).ajaxSuccess(function (event, xhr, settings) {
alert("sucess");
});
7. 跨域获取json$.ajax({
type: "POST",
dataType: "jsonp",
url: "http://www.li.cc/jsonp.php",
success: function (resposne, status, xhr) {
alert(response);
}
})
8. jqXHR对象
jqXHR就是$.ajax();返回的对象
var jqXHR = $.ajax({
type: "POST",
dataType: "jsonp",
url: "http://www.li.cc/jsonp.php"
}
jqXHR.success(function (response) {
alert(response);
}); //success, error, complete将要被取消
jqXHR.done(function (response) {
alert(response); //等价于success, 好处支持多个done回调函数。
});
jqXHR.always(function (response) {
alert(response); //等价于complete
});
jqXHR.fail(function (response) {
alert(response); //等价于error
});
$.when(jqXHR1, jqXHR2).done(function (r1, r2) {
console.log(r1, r2); //同时处理两个jqxhr.
})