处理jquery ajax错误

时间:2013-03-13 07:49:11

标签: javascript asp.net-mvc jquery asp.net-mvc-4

在我的MVC布局页面中,我有以下内容:

$("body").ajaxError(
    function (e, request) {
        if (request.status == 403 || request.status == 500) {
            window.location = '@Url.Action("LogOn", "Account", new {area = "", msg = "forbidden", returnUrl = HttpContext.Current.Request.RawUrl})' + window.location.hash;
        return;
        }
        window.location = '@Url.Action("Index", "Error")';
    }
);

在另一个页面上我正在执行ajax调用:

...
                $.when(refreshActionLinks(row, machineId, packageId)).done(function(a1) {
                    row.find("span").text(opStatus).removeClass("pending");
                    progressbar.progressbar("destroy");
                    $(row).flash(bg[1], 1000);
                });
...

javascript函数:

function refreshActionLinks($row, machineId, packageId) {
    try {
        var json = JSON.stringify({ packageId: packageId, machineId: machineId, tabType: $("#TabType").val() });
        console.log("refreshActionLinks => " + json);
        $row.find("td.options div.actionLinks").html("<img src='@Url.Content("~/Content/images/ajax-load2.gif")' />"); // pending
        return $.ajax({
            url: "@Url.Action("GetActionLinks", "Packages")",
            data: json,
            timeout: 50000,
            contentType: 'application/json',
            type: 'POST',
            success: function (data) {
                if ($row.length) {
                    $row.find("td.options div.actionLinks").html(data);
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(textStatus, errorThrown);
            }
        });
    } catch(e) {
        // hide icons
        $row.find("a.action").remove();
    } 
}

问题在于,当执行refreshAction函数时,单击菜单链接会导致ajax调用错误 - 在这种情况下是正确的。但它确实需要我/ / Index / Error页面不正确。我想“ $(”body“)。ajaxError ”处理网站上的所有ajax错误除了我正在调用refreshActionLinks的页面上的EXCEPT。请注意,我已经尝试/捕获我的ajax调用。为什么不起作用?

感谢

1 个答案:

答案 0 :(得分:0)

想通了:

ajax有一个设置:

global: false

现在我的功能看起来像这样:

function refreshActionLinks($row, machineId, packageId) {
    try {
        var json = JSON.stringify({ packageId: packageId, machineId: machineId, tabType: $("#TabType").val() });
        console.log("refreshActionLinks => " + json);
        $row.find("td.options div.actionLinks").html("<img src='@Url.Content("~/Content/images/ajax-load2.gif")' />"); // pending
        return $.ajax({
            url: "@Url.Action("GetActionLinks", "Packages")",
            global: false, // disable error pages on failed ajax calls
            data: json,
            timeout: 50000,
            contentType: 'application/json',
            type: 'POST',
            success: function (data) {
                if ($row.length) {
                    $row.find("td.options div.actionLinks").html(data);
                }
            }
        });
    } catch(e) {
        // hide icons
        $row.find("a.action").remove();
    } 
}