2010-02-01 57 views
16

我有一個jQuery代碼,我使用get()並調用一些遠程url /文件。 現在我想知道什麼是處理錯誤的最好方法。

什麼我做的是:

$(document).ready(function() { 
     $.ajaxSetup({ 
      error: function(x, e) { 

       if (x.status == 0) { 
        alert(' Check Your Network.'); 
       } 
        else if (x.status == 404) { 
       alert('Requested URL not found.'); 

       } else if (x.status == 500) { 
        alert('Internel Server Error.'); 
       } else { 
        alert('Unknow Error.\n' + x.responseText); 
       } 
      } 
     }); 

     $.get("HTMLPage.htm", function(data) { 
      alert(data); 
      $('#mydiv').html(data); 

     }); 
    }); 

這是工作fine.But想知道有沒有這樣做的沒有更好的辦法?

裁判:http://www.maheshchari.com/jquery-ajax-error-handling/

+0

這是一個體面的AJAX錯誤處理對我來說。 – RaYell 2010-02-01 10:11:51

+1

定義更好?您想要改進的現有代碼有什麼問題? – 2010-02-01 10:27:41

+0

如果你想改進你的代碼,你可以停止使用提醒並使用更加用戶友好的功能。你實際上是唯一一個想看到這個錯誤信息的人。您可以在某處顯示模式屏幕或小文本框,告訴用戶發生了錯誤。 – 2012-03-27 12:00:54

回答

15

使用$ .ajaxSetup是對所有Ajax調用。由於$ .get函數沒有任何錯誤回調,因此在$ .ajaxSetup中定義錯誤處理程序是處理錯誤的唯一方法。如果您使用$阿賈克斯,您可以定義在$就調用錯誤處理這樣

$.ajax({ 
    url: "HTMLPage.htm", 
    success: function(data) { 
    alert(data); 
    $('#mydiv').html(data);   
    }, 
    error: function(XMLHttpRequest, textStatus, errorThrown) { 
    if (XMLHttpRequest.status == 0) { 
     alert(' Check Your Network.'); 
    } else if (XMLHttpRequest.status == 404) { 
     alert('Requested URL not found.'); 
    } else if (XMLHttpRequest.status == 500) { 
     alert('Internel Server Error.'); 
    } else { 
     alert('Unknow Error.\n' + XMLHttpRequest.responseText); 
    }  
    } 
}); 

這是特定於僅此Ajax調用,這樣你可以有更具體的錯誤消息。但使用全局錯誤處理程序也可以。

你可以從http://api.jquery.com/jQuery.ajax/定義$(文件)。就緒()這樣的

$(document).ready(function() { 
    $.ajaxSetup({ 
     error: AjaxError 
    }); 

    $.get("HTMLPage.htm", GetSuccess); 
}); 

function AjaxError(x, e) { 
    if (x.status == 0) { 
    alert(' Check Your Network.'); 
    } else if (x.status == 404) { 
    alert('Requested URL not found.'); 
    } else if (x.status == 500) { 
    alert('Internel Server Error.'); 
    } else { 
    alert('Unknow Error.\n' + x.responseText); 
    } 
} 

function GetSuccess(data) { 
    alert(data); 
    $('#mydiv').html(data); 
} 
+1

感謝您爲這個問題寫了這麼好的迴應!我特別讚賞關於移動$ .ajaxSetup()調用之外的函數定義的提示。 – Steph 2012-07-04 20:46:20

1

複製/粘貼之外的功能:

的StatusCode(增加1.5){}
數字HTTP代碼和 函數在 響應具有相應代碼時調用。 例如,下面將提醒 當響應狀態爲404:

$.ajax({ 
    statusCode: {404: function() { 
    alert('page not found'); 
    } 
}); 

如果請求成功,則 狀態碼功能採取同樣 參數作爲成功回調;如果 它導致錯誤,他們採取與錯誤回調相同的參數 。

+0

這對我不起作用,調用是'$ .ajaxSetup',然後是'{statusCode:...}'等。 – Diziet 2014-08-13 11:39:04

0

從jQuery 1.5開始,所有jQuery的Ajax方法都返回一個XMLHTTPRequest對象的超集。這個jQuery XHR對象或$ .get()返回的「jqXHR」實現了Promise接口,爲Promise提供了所有屬性,方法和行爲。

var jqxhr = $.get("example.php", function() { 
    alert("success"); 
}) 
.done(function() { 
    alert("second success"); 
}) 
.fail(function() { 
    alert("error"); 
}) 
.always(function() { 
    alert("finished"); 
});