简体   繁体   English

jQuery解析从控制器返回的JSON结果

[英]jQuery parsing JSON results returned from controllers

I want to parse JSON results, containing status or error messages, returned from controller method or custom exception filter and display the messages. 我想解析包含状态或错误消息的JSON结果,从控制器方法或自定义异常过滤器返回并显示消息。

     $.ajax({
        url: "/Account/LogOn",
        type: "POST",
        dataType: "json",
        data: form.serialize(),
        success: function (result) {
            alert(result);     
        }
    });

I think that with this code I can do it for a specific Action Result or method. 我认为使用此代码我可以针对特定的Action Result或方法执行此操作。 Is there a way to do this for every JSON result returned to the page? 有没有办法为返回到页面的每个JSON结果执行此操作?

No, there's no way to do this for every possible JSON returned by your controller actions because the structure will be different and the properties of this result variable won't be the same. 不,对于控制器操作返回的每个可能的JSON,都无法执行此操作,因为结构将不同,并且此result变量的属性将不相同。

The correct way would be to have a custom error handler which will intercept all exceptions and wrap them in a well defined JSON structure. 正确的方法是拥有一个自定义错误处理程序,它将拦截所有异常并将它们包装在一个定义良好的JSON结构中。 Then you could use the error callback in the AJAX request to handle this case. 然后你可以使用AJAX请求中的错误回调来处理这种情况。

public class AjaxErrorHandler : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            filterContext.Result = new JsonResult
            {
                Data = new
                {
                    ErrorMessage = filterContext.Exception.Message
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 500;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }
    }
}

which could be registered as a global action filter: 可以注册为全局动作过滤器:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new AjaxErrorHandlerAttribute());
}

and on the client you could also have a global AJAX error handler for all AJAX requests on the same page: 在客户端上,您还可以在同一页面上为所有AJAX请求提供全局AJAX错误处理程序:

$(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
    var json = $.parseJSON(jqXHR.response);
    alert(json.ErrorMessage);
});
$.ajax({
    url: "/Account/LogOn",
    type: "POST",
    dataType: "json",
    data: form.serialize(),
    success: function (result) {
        alert(result);     
    }
    error: function (req, status, error) {
        //your logic
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM