Jquery $.ajax状态码Else

23

在一个jQuery的Ajax调用中,我目前处理的状态码为200和304。但是我也定义了"Error"以捕获可能返回的任何错误。

如果有相关的验证消息,则返回状态码400 - 错误请求。

这会先进入"Error"函数,然后再进入我定义的statusCode "400"函数。这意味着会发生两个动作。

理想情况下,我不想定义"Error"和"Success",只定义"statusCode"。但我需要一个"Else",这样我就不需要声明每个存在的statusCode,只需处理2-3个不同的statusCode。

$.ajax({
        type: 'POST',
        contentType: "application/json",
        url: "../API/Employees.svc/" + EmployeeId + "/Company/" + CompanyId,
        data: jsonString,
        statusCode: {
            200: function () { //Employee_Company saved now updated

                hideLoading();
                ShowAlertMessage(SaveSuccessful, 2000);
                $('#ManageEmployee').dialog('close');

            },
            304: function () { //Nothing to save to Employee_Company

                hideLoading();
                $('#ManageEmployee').dialog('close');

                if (NothingToChange_Employee) {
                    ShowAlertMessage(NothingToUpdate, 2000);
                } else {
                    ShowAlertMessage(SaveSuccessful, 2000);
                }
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            AjaxError(XMLHttpRequest, textStatus, errorThrown);
        }
    });
4个回答

30

由于“complete”事件总是被触发,您可以从中获取状态码并忽略成功和错误函数。

complete: function(e, xhr, settings){
    if(e.status === 200){

    }else if(e.status === 304){

    }else{

    }
}

这似乎运行得相当不错,是一个很好的答案,尽管在我的情况下,我最终实际上使用了成功和失败两者,并在每个中使用了与您上面相似的if语句。 - Steve
12
complete()已被弃用,请使用done、fail和always替代方法。 - redochka

10

这是我会使用的:

error: function (xhr, textStatus, errorThrown) {
    switch (xhr.status) {
        case 401:
           // handle unauthorized
           break;
        default:
           AjaxError(xhr, textStatus, errorThrown);
           break;
    }
}

5

jQuery AJAX响应completesuccesserror已经被弃用。最新版本使用.done.fail.always代替。

在成功时,.always的签名与.done相同;在失败时,其签名会改变为.fail的签名。使用textStatus可以获取正确的变量并返回主体内容。

var jqxhr = $.ajax( {
    type: frm.attr('method'),
    url: frm.attr('action'),
    data: frm.serialize(),
    dataType: 'json',
    } )

    .done(function( data, textStatus, jqXHR ) {
        alert( "success" );
    })
    .fail(function( jqXHR, textStatus, errorThrown ) {
        alert( "error" );
    })

    .always(function( data_jqXHR, textStatus, jqXHR_errorThrown ) {

        if (textStatus === 'success') {
            var jqXHR = jqXHR_errorThrown;
        } else {
            var jqXHR = data_jqXHR;
        }
        var data = jqXHR.responseJSON;

        switch (jqXHR.status) {
            case 200:
            case 201:
            case 401:
            default:
                console.log(data);
                break;
        }   

});

jqxhr.always(function() {
    alert( "second complete" );
});

1
jqXHR.error()已被弃用,而不是jQuery.ajax()中的error选项。 不知道它是否随之被隐式弃用,但至少没有记录为已弃用。 - falstro

1
为了保持与您最初的逻辑相似,我会继续传递一个statusCode对象。但是,您仍然知道"else"将属于4xx或5xx类型的错误代码范畴。
因此,我会更新您的原始代码为:
var statusCodeResponses = {
    200: function () { //Employee_Company saved now updated

        hideLoading();
        ShowAlertMessage(SaveSuccessful, 2000);
        $('#ManageEmployee').dialog('close');

    },
    304: function () { //Nothing to save to Employee_Company

        hideLoading();
        $('#ManageEmployee').dialog('close');

        if (NothingToChange_Employee) {
            ShowAlertMessage(NothingToUpdate, 2000);
        } else {
           ShowAlertMessage(SaveSuccessful, 2000);
        }
    }
};

var genericElseFunction = function(response){
    // do whatever other action you wanted to take
};

for(var badResponseCode=400; badResponseCode<=599; badResponseCode++){
     statusCodeResponses[badResponseCode] = genericElseFunction;
}

$.ajax({
    type: 'POST',
    contentType: "application/json",
    url: "../API/Employees.svc/" + EmployeeId + "/Company/" + CompanyId,
    data: jsonString,
    statusCode: statusCodeResponses,
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        AjaxError(XMLHttpRequest, textStatus, errorThrown);
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接