【问题标题】:Getting properties from JsonResult on the JS side inside jquery ajax在 jquery ajax 的 JS 端从 JsonResult 获取属性
【发布时间】:2011-11-23 21:43:51
【问题描述】:

我正在返回以下对象 JsonResult

return new JsonResult
            {
                Data = new { ErrorMessage = message },
                ContentEncoding = System.Text.Encoding.UTF8,
                JsonRequestBehavior = JsonRequestBehavior.DenyGet
            };

如何在 jquery 端获取错误消息?

这是我的 jquery ajax 错误委托

error: function (result) {
        alert('error');
        alert(result.ErrorMessage);
    }

但它警告为未定义。我试过result.Data 以及result.message....所有undefined

namespace myApp.ActionFilters
{
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
    public class AjaxException : ActionFilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            if (!filterContext.HttpContext.Request.IsAjaxRequest()) return;

            filterContext.Result = AjaxError(filterContext.Exception.Message, filterContext);

            //Let the system know that the exception has been handled
            filterContext.ExceptionHandled = true;
        }

        protected JsonResult AjaxError(string message, ExceptionContext filterContext)
        {
            //If message is null or empty, then fill with generic message
            if (String.IsNullOrEmpty(message))
                message = "Something went wrong while processing your request. Please refresh the page and try again.";

            //Set the response status code to 500
            filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

            //Needed for IIS7.0
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;

            return new JsonResult
            {
                Data = new { ErrorMessage = message },
                ContentEncoding = System.Text.Encoding.UTF8,
                JsonRequestBehavior = JsonRequestBehavior.DenyGet
            };
        }
    }
}

在我的控制器中,我有一个动作来测试这个

 [AjaxException]
    public ActionResult TestErrorHandling(string id)
    {
       if (string.IsNullOrEmpty(id))
        {
            throw new Exception("oh no");
        }
        return Json(new { success = true });
     }

在我的 js 中

 id = "";
 $.ajax({
    contentType: 'application/json, charset=utf-8',
    type: "POST",
    url: "/Controller/TestErrorHandling",
    data: JSON.stringify({ id: id }),
    cache: false,
    dataType: "json",

    success: function (result) {
        alert('some error occurred: ' + result.ErrorMessage);


        alert('success!');
    },

    error: function (xhr, ajaxOptions, thrownError) {
        alert('error');
        alert(xhr.ErrorMessage);
    }

    });

问题:如何在错误委托中获取 errorMessage?

【问题讨论】:

  • 您的代码的第一部分似乎在语法上无效。构造函数的参数应该总是用单括号括起来,而不是花括号。此外,在 new 关键字之后必须始终是函数,而不是对象。希望对您有所帮助。
  • @Betamos,您可能应该阅读 C# 中的对象和集合初始化器语法:msdn.microsoft.com/en-us/library/bb384062.aspx
  • @DarinDimitrov 哦,哈哈。对不起。以为都是JS。请忽略我之前的评论。
  • @Betamos,哦不,这根本不是你的错。正确标记他的问题并将其置于上下文中是 OP 的错。他甚至没有提到他最初使用的是 asp.net-mvc,这可能完全解释了人们的困惑。他用 javascript 和 jquery 标记它,显然他展示的代码对 javascript 没有任何意义。

标签: jquery asp.net-mvc json


【解决方案1】:

如何在 jquery 端获取错误消息?

由于您返回的 JSON 对象带有 200 个状态码,因此永远不会执行错误回调。所以你可以在这种情况下使用success 回调:

success: function(result) {
    if (result.ErrorMessage) {
        alert('some error occurred: ' + result.ErrorMessage);
    }
}

或者,如果您希望执行错误处理程序,请确保在控制器操作中设置正确的状态代码:

public ActionResult Foo()
{
    Response.StatusCode = 500;
    return Json(new { ErrorMessage = message });
}

然后:

error: function (jqXHR) {
    var result = $.parseJSON(jqXHR.responseText);
    alert('some error occurred: ' + result.ErrorMessage);
}

您可能还会发现following answer 很有用。

【讨论】:

  • 实际上,错误回调确实被执行了。 .....它警告'错误'然后'未定义'
  • 我比以前更困惑了:)哈哈。这个 jquery 错误似乎是 jquery web dev 中最神秘的部分。关于如何在 JS 端正确处理错误处理和捕获自定义错误消息,在线任何地方都没有明确的文档。
  • @sarsnake,你有什么困惑?阅读文档:api.jquery.com/jQuery.ajax 当服务器返回不同于 200 的 HTTP 状态代码时,将调用错误处理程序。在您的代码中,您返回状态代码为 200 的 JsonResult => 不会调用错误回调是正常的。对于 jQuery,如果服务器返回 200 状态码,则表示成功并且有意义。
  • @sarsnake,嗯,那么可能有异常或被抛出的东西,或者由于 javascript 错误而根本没有触发 AJAX 调用。例如,使用 FireBug 之类的调试工具来了解幕后发生的事情。在这方面我无能为力了。
  • 我将返回上述 JsonResult 作为异常处理的一部分。我将发布完整代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-17
  • 1970-01-01
  • 1970-01-01
  • 2011-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多