加載請求: .ajaxStart() 和 .ajaxstop()
$(document).ajaxStart(function(){ $('.loading').show(); }).ajaxStop(function(){ $('.loading').hide(); });
錯誤處理: .ajaxError()
//1 $.ajax()使用屬性提示錯誤 $('form input[type=button]').click(function(){ $.ajax({ type:"post", url:"test1.php", async:true, data:$('form').serialize(), success:function(response,status,xhr){ $('#box').html(response); }, // timeout:3000 // global:false error:function(xhr,errorText,errorType){ // alert(errorText + ':' +errorType); alert(xhr.status + ':' +xhr.statusText); } }); }); //2 $.post()使用連綴.error()方法提示錯誤,將被.fail()取代 $('form input[type=button]').click(function(){ $.post('test1.php').error(function(xhr,errorText,errorType){ alert(errorText + ':' +errorType); alert(xhr.status + ':' +xhr.statusText); }); }); //3 使用全局.ajaxError()方法 $(document).ajaxError(function(event,xhr,settings,info){ alert(event.type); alert(event.target); for(var i in event){ //打印出event的所有屬性 document.write(i + '<br />'); } });
.ajaxSuccess(),對應一個局部方法:.success(),請求成功完成時執行。
.ajaxComplete(),對應一個局部方法:.complete(),請求完成后注冊一個回調函數。
.ajaxSend(),沒有對應的局部方法,只有屬性 beforeSend,請求發送之前要綁定的函數。
//$.post()使用全局 $('form input[type=button]').click(function(){ $.post('test.php',$('form').serialize()); }); $('document').ajaxSend(function(){ alert(發送請求之前執行); }).ajaxComplete(function(response,status,xhr){ alert('請求完成后,不管是否失敗成功'); }).ajaxSuccess(function(event,xhr,settrings){ alert('請求成功后,不管是否成功'); }).ajaxError(function(event,xhr,settrings){ alert('請求失敗后'); }); //$.post()使用局部 $('form input[type=button]').click(function(){ $.post('test.php',$('form').serialize()).success(function(){ alert('請求成功后'); }).complete(function(){ alert('請求完成后'); }).error(function(){ alert('請求失敗后'); }); }); //$.ajax()使用屬性 $('form input[type=button]').click(function(){ $.ajax({ type:"post", url:"test1.php", async:true, data:$('form').serialize(), success:function(response,status,xhr){ alert('請求成功后'); }, complete:function(){ alert('請求完成后,不管失敗成功'); }, beforeSend:function(){ alert('發送請求之前'); }, error:function(xhr,errorText,errorType){ alert('請求失敗后'); } }); });
注:
在 jQuery1.5 版本以后,使用.success()、.error()和.complete()連綴的方法,可以用.done()、.fail()和.always()取代。