什么HTTP响应代码jQuery aJax错误处理程序认为'错误'?

sos*_*sil 4 javascript c# asp.net ajax jquery

我有一个标准的aJax回调到服务器:

$.ajax({
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        url: '/Apps/ResetDateAndCount',
        data: JSON.stringify({
            appName: app
        }),
        success: function (response) {
            $('.lastReset').text(response);
            $('.currentCount').text('0');
        },
        error: function (xhr, status, error) {
            alert("You are not authorized to perform that action");
        }
    });
Run Code Online (Sandbox Code Playgroud)

从我的服务器(ASP.NET)我返回错误,如:

return Json(new { success = false, error = "You are not authorized to perform that action" });
Run Code Online (Sandbox Code Playgroud)

Response.StatusCode = 401; return Json(new { success = false, error = "You are not authorized to perform that action" });
Run Code Online (Sandbox Code Playgroud)

Response.StatusCode = 500; return Json(new { success = false, error = "You are not authorized to perform that action" });
Run Code Online (Sandbox Code Playgroud)

在错误处理程序内部,当状态代码设置为时,error: function (xhr, status, error) 只有最后一个返回将被捕获为错误500.

我想知道什么响应代码aJax实际上认为是"错误"?

Dar*_*rov 9

jQuery在进行AJAX调用时,任何超出区间[200,299]且不同于304的错误代码都被视为错误.

现在当然你会问我,这很好,花花公子,但为什么这不被认为是一个错误,毕竟我返回401在上述间隔之外所以它应该被认为是一个错误:

Response.StatusCode = 401; 
return Json(new { success = false, error = "You are not authorized to perform that action" });
Run Code Online (Sandbox Code Playgroud)

非常简单:因为当您从ASP.NET MVC中的控制器操作返回401状态代码时,框架(更具体地说是ASP.NET Forms身份验证模块)将拦截此请求并将您重定向到登录表单,最终导致200状态代码.是的,登录页面提供200 OK状态代码.在这种情况下,200位于区间内,因此不会error调用回调.您可以通过检查success针对此特定情况的回调中返回的登录页面的DOM来验证这一点.

现在将自己置于浏览器发出AJAX请求的角度:它将遵循服务器所做的所有重定向,直到它到达最终目的地.如果此最终目标状态代码超出了间隔且不同于304,那么您将获得error调用的回调.好的,现在事情开始变得更有意义了.

所以你要问我的下一个问题是,如果我从控制器操作中返回401状态代码,如何调用错误回调,对吧?然后我会将你(:-))重定向到以下博客文章:Prevent Forms Authentication Login Page Redirect When You Don't Want It.