如何避免$ .ajaxPrefilter()的http错误代码500,404而不是401?

时间:2017-01-11 06:37:30

标签: jquery ajax http-status-code-401

我试图拦截ajax响应以处理ajax的失败(HTTP错误代码401,404或500等)。 我研究过我们可以通过使用$ .ajaxPrefilter()来做到这一点。所以我尝试了,并取得了成功。这是我的代码,

//the ajax call
$.ajax({
    type: "POST",
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    url: "getPrevActivityLogs",
    data: JSON.stringify({
        'startDate': startDate,
        'finishDate': endDate
    }),
    dataType: "json",
    success: function (data) {
//todo the codes for successfully ajax response
    }, error: function (data, status) {
        showToastr('Unexpected Server Exception ' + data["message"] + " " + status, 'Activity Load', 'error');
    }
}); 

现在拦截ajax的代码

$.ajaxSetup(
    {
       normalizeForStatusCodes: true
    }
);

在ajaxPrefilter的代码下面:

$.ajaxPrefilter(
    function( options, localOptions, jqXHR ){
        if (options.normalizeForStatusCodes){
            normalizeAJAXRequestForStatusCodes( jqXHR );// the function where we can play with the success and the failure of ajax call
        }
    }
);

我们决定在ajax中出现错误时要做什么的函数

function normalizeAJAXRequestForStatusCodes( jqXHR ){
    var normalizedRequest = $.Deferred();
    jqXHR.then(
        normalizedRequest.resolve,
        function (jqXHR ) {
            var msg;
            if (jqXHR.status == 401){
                if($("#login-flow-modal").data('bs.modal') != undefined){ // checks if modal opened 
                    msg = getLoginErrorMessage(jqXHR.responseText);
                }else{
                    msg = ''; // initialise to remove previous error messages
                }
                normalizedRequest.rejectWith(
                    this,
                    [
                        loadLoginFlowModal(msg),
                        "error",
                        jqXHR
                    ]
                )

            }else {
                normalizedRequest.rejectWith(
                    this,
                    [
                        $.parseJSON( jqXHR.responseText ),
                        "success",
                        jqXHR
                    ]
                );
            }
        }
    )
    jqXHR = normalizedRequest.promise( jqXHR );
    jqXHR.success = jqXHR.done;
    jqXHR.error = jqXHR.fail;
 }
}

现在这些代码运行得很好。我能够拦截错误401的ajax。

我的要求是,我想拦截401错误代码。应将每个错误代码(例如500,404等)重定向到原始的ajax调用以进行自定义处理。

0 个答案:

没有答案