2011-01-14 125 views
13

當您使用$ .get或$ .post時,如何捕獲Server Error或404頁面未找到?

例如:

$.post("/myhandler", { value: 1 }, function(data) { 
    alert(data); 
}); 

那將什麼都不做,如果有一個服務器錯誤裝載「/將myHandler」,或者,如果沒有找到它。

如果出現錯誤,您如何通知您?

回答

20

使用error處理器上$.ajax()

$.ajax({ 
    url: "/myhandler", 
    data: {value: 1}, 
    type: 'post', 
    error: function(XMLHttpRequest, textStatus, errorThrown){ 
     alert('status:' + XMLHttpRequest.status + ', status text: ' + XMLHttpRequest.statusText); 
    }, 
    success: function(data){} 
}); 

demo

+6

因此,這是不可能的$不用彷徨? – 2013-01-17 21:52:03

+0

同上,可以做類似的負載()? – 2014-01-18 05:42:02

5

其他的答案很不錯,一切,但有替代解決方案,即.ajaxSetup.ajaxError和其他Ajax事件處理程序(檢查ajaxSetup文檔頁面的其他信息)。

例如,.ajaxError你可以設置從.post.get.getJSON.ajax所有你的Ajax錯誤的一組特定元素的一個全球性的處理程序。

$(selector).ajaxError(function(event, xhr, ajaxOptions, errorThrown) { 
    // handle ajax error here 
}); 
33

你可以做

$.post("/myhandler", { value: 1 }, function(data) { 
    alert(data); 
}).fail(function(){ 
    // Handle error here 
}); 

失敗將被調用,如果那裏有一個錯誤

1

嘗試使用$.ajaxSetup()stausCode選項

$.ajaxSetup({ 
    statusCode : { 
    // called on `$.get()` , `$.post()`, `$.ajax()` 
    // when response status code is `404` 
    404 : function (jqxhr, textStatus, errorThrown) { 
      console.log(textStatus, errorThrown); 
      } 
    } 
}); 

// $.get("/path/to/url/"); 
// $.post("/path/to/url/"); 
// $.ajax({url:"/path/to/url/"})