javascript - AJAX 错误返回为成功

标签 javascript jquery ajax asp.net-mvc

AJAX 错误作为成功返回。如何从 ASP.NET MVC 返回 JSON 错误?你能告诉我我做错了什么吗?谢谢。

[HttpPost]
    public JsonResult Register(int EventID)
    {
        try
        {
            // code
            return Json(new { success = true, message = "Thank you for registering!" });
        }
        catch (Exception ex)
        {
            return Json(new { success = false, message = ex.Message });
        }
    }


                $.ajax({
                    url: "@Url.Action("Register", "Home")",
                    type: "post",
                    dataType: "json",
                    contentType: "application/json",
                    data: JSON.stringify(postData),
                    success: function(data) {
                    },
                    error: function (data) {
                    }
                });

最佳答案

仅当 HTTP 响应代码不是 HTTP 200 Ready 时,才会执行 error 函数。您在服务器端处理错误并返回正确的响应,该响应将由 AJAX 调用中的 success 函数获取。相反,请在 JSON 中使用 status 变量并在客户端处理它:

success: function(data) {
  if (typeof data == "string")
    data = JSON.parse(data);
  if (data.success) {
    // Code if success.
  } else {
    // Code if error.
  }
},

来自docs (向下滚动到错误部分):

A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event.

关于javascript - AJAX 错误返回为成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37187699/

相关文章:

javascript - 使用 JavaScript 进行 HTML5 验证

jquery - Superfish 子菜单不显示

javascript - window.location.href 和 location.reload() 不从服务器加载更新的页面

javascript - JSON.parse 没有错误但不起作用

javascript - 使用 formdata 进行多部分文件上传

javascript - 抽象类中用于创建 self 实例的 Typescript 静态方法

javascript - 关于 JavaScript 中尾随逗号的问题

javascript - 无法获取订阅函数内组件的 'this'

javascript - 通过 addEventListener 添加的事件监听器被多次调用

javascript - jQuery 宽度 (%) 不会在 windowResize 上停止计算?