10

据我了解,使用 ajax 处理错误结果的一种可能性是:

$.ajax({
    url: someUrl,
    type: 'POST',
    success: function(data) {},
    error: function(jqXHR, exception) {
        if (jqXHR.status === 0) {
            alert('Not connect.\n Verify Network.');
        } else if (jqXHR.status == 404) {
            alert('Requested page not found. [404]');
        } else if (jqXHR.status == 500) {
            alert('Internal Server Error [500].');
        } else if (exception === 'parsererror') {
            alert('Requested JSON parse failed.');
        } else if (exception === 'timeout') {
            alert('Time out error.');
        } else if (exception === 'abort') {
            alert('Ajax request aborted.');
        } else {
            alert('Uncaught Error.\n' + jqXHR.responseText);
        }
    }
});

或使用statusCode以使其更具可读性:

$.ajax({
    url: someUrl,
    type: 'POST',
    statusCode: {
        200: function(data) {
                   :
                   :
             },
        401: function() {
                   :
                   :
             },
              :
              :

我的问题是:
是否有可能使用statusCode并有一个默认的失败?

4

1 回答 1

20

不在 statusCode 参数中。但那是因为如果你想抓住一切,这是一种更好(更精简)的方式:

complete: function(jqXHR, textStatus) {
    switch (jqXHR.status) {
        case 200:
            alert("200 received! yay!");
            break;
        case 404:
            alert("404 received! boo!");
            break;
        default:
            alert("I don't know what I just got but it ain't good!");
    }
}
于 2012-07-26T23:53:01.300 回答