Javascript Jquery $.ajax statusCode Else

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10042040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:36:46  来源:igfitidea点击:

Jquery $.ajax statusCode Else

javascriptjqueryajaxhttp-status-codes

提问by Steve

In a jquery Ajax call I am currently handling statusCode of 200 and 304. But I also have "Error" defined" To catch any Errors that could come back.

在 jquery Ajax 调用中,我目前正在处理 200 和 304 的 statusCode。但我也定义了“错误”以捕获任何可能返回的错误。

If there is a validation message related we return the status code of 400 - Bad Request.

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

This then falls into the "Error" function before falling into the statusCode "400" function I had defined. Which means two actions happen.

然后在落入我定义的状态码“400”函数之前,它落入“错误”函数中。这意味着发生了两个动作。

Ideally I would like to not define "Error" and "Success" and only define "statusCode" But what I need is to have a "Else" so that I don't need to declare every statusCode that exists only the 2-3 I want to handle differently.

理想情况下,我不想定义“错误”和“成功”而只定义“状态代码”但我需要的是有一个“其他”,这样我就不需要声明只存在 2-3 个我的每个状态代码想以不同的方式处理。

$.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);
        }
    });

回答by Nicola Peluchetti

Since the "complete" event is always fired you could simply get the status code from there and ignore the success and error functions

由于“完成”事件总是被触发,您可以简单地从那里获取状态代码并忽略成功和错误功能

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

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

    }else{

    }
}

回答by Muxa

This is what i'd use:

这就是我要使用的:

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

回答by MrYellow

jQuery AJAX response complete, success, errorhave been deprecated. More up-to-date version with .done, .fail, .alwayspromise instead.

jQuery AJAX 响应completesuccesserror已被弃用。使用.done, .fail, .alwayspromise 代替更新的版本。

On success .alwayshas signature of .done, on failure it's signature changes to that of .fail. Using the textStatusyou can grab the correct variable and return the body contents.

成功时.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" );
});

回答by Scott Lobdell

To keep the approach similar to your initial logic, I would continue passing a statusCode object. However, you still know that "else" will fall in the realm of 4xx or 5xx type error codes.

为了使方法与您的初始逻辑相似,我将继续传递一个 statusCode 对象。但是,您仍然知道“else”将落入 4xx 或 5xx 类型错误代码的范围内。

So I would update your original code to:

因此,我会将您的原始代码更新为:

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);
    }
});