Jquery $.ajax statusCode Else

2019-02-07 21:04发布

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.

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

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

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.

$.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条回答
仙女界的扛把子
2楼-- · 2019-02-07 21:47

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;
    }
}
查看更多
老娘就宠你
3楼-- · 2019-02-07 21:52

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.

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);
    }
});
查看更多
叼着烟拽天下
4楼-- · 2019-02-07 21:53

jQuery AJAX response complete, success, error have been deprecated. More up-to-date version with .done, .fail, .always promise instead.

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

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" );
});
查看更多
ゆ 、 Hurt°
5楼-- · 2019-02-07 22:07

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{

    }
}
查看更多
登录 后发表回答