jquery $ .ajaxSetup()处理ajax错误

时间:2013-04-18 10:56:50

标签: c# jquery asp.net-mvc asp.net-mvc-4 razor

我想在发生错误时添加(默认)操作,而不是(403,500或410代码):

    $.ajaxSetup({
        statusCode: {
            403: function () {
                window.location = '@Url.Action("LogOn", "Account", new {area = "", msg = "forbidden", returnUrl = HttpContext.Current.Request.RawUrl})' + window.location.hash;
            },
            500: function() {
                window.location = '@Url.Action("AccessDenied", "Error")';
            },
            410: function() {
                window.location = '@Url.Action("Deleted", "Error")';
            }
            // ANY OTHER ERROR CODE - but it doesn't work, how can i do it?
            if not any above and it's an error then =>
            window.location = '@Url.Action("Index", "Error")';
        }
    });

2 个答案:

答案 0 :(得分:2)

您应该使用ajaxError()来处理错误 ajaxSetup()

$(document).ajaxError(function(event, xhr, options) {
     switch (xhr.status)
     {
        case 403:
            window.location = '@Url.Action("LogOn", "Account", new {area = "", msg = "forbidden", returnUrl = HttpContext.Current.Request.RawUrl})' + window.location.hash;
        break;
        case 500:
            window.location = '@Url.Action("AccessDenied", "Error")';
        break;
        case 410:
            window.location = '@Url.Action("Deleted", "Error")';
        break;
        default:
            window.location = '@Url.Action("Index", "Error")';
        break;
     }
   }
});

答案 1 :(得分:0)

“完整”事件总是被触发。

complete: function(jqXHR, textStatus) {
    switch (jqXHR.status) {
        case 200:
            alert("error 200");
            break;
        case 404:
            alert("error 404");
            break;
        default:
            alert("DEFAULT");
    }
}