在$ .ajax失败函数中获取处理错误

时间:2015-12-16 11:30:31

标签: jquery ajax asp.net-mvc

以下是我的ajax调用代码。我有一个Asp.net MVC作为后端应用程序。

   $.ajax({
            url: someUrl,
            method: 'get',
            dataType : 'html'
        }).success(function (result) {
            $("#mainDiv").html(result);
            ajaxindicatorstop();
        })
        .fail(function (data, status, error) {                
            handleFailedAjax();
            ajaxindicatorstop();
        });

当我的应用程序抛出任何错误时,它仍会执行成功回调而不是失败。 我的猜测是,因为我使用global.asax中的Application_Error处理了服务器端的所有错误,所以jquery没有看到任何错误并且成功地给我状态200(OK)。有什么方法我仍然可以获得错误状态代码并获得执行ajax调用的失败部分。

在我的应用程序中,我有混合类型的ajax调用,结果是期望json或html。

错误处理程序始终返回html(通用错误消息)。由于这个原因,我使用dataType'json'的ajax调用失败并转到错误/失败回调(没有关于实际错误)。

1 个答案:

答案 0 :(得分:0)

您可以使用此代码

$(document).ajaxError(
    function (e, request) {
        if(request.status !== 200){
            // code here..
        }
    }   
);