覆盖特定状态代码的 jQuery 默认 ajaxError

Des*_*901 2 javascript ajax jquery

我正在尝试为 AJAX 调用实现一个 jQuery 默认 HTTP 错误处理程序。我已经为通用应用程序错误实现了默认错误处理程序,如下所示:

$(document).ajaxError(function(event, jqXHR, settings, thrownError) {
    switch (jqXHR.status) {
        case 403:
            console.log('Forbidden, go away!');
            break;
        case 404:
            console.log('Resource not found :O');
            break;
        case 422:
            console.log('Unprocessable entity.');
            break;
        case 500:
            console.log('Someone have to pay for this!');
            break;
        default:
            console.log('Anyone knows what is going on here?');
    }
});
Run Code Online (Sandbox Code Playgroud)

现在我想要实现的是在单个 AJAX 调用中覆盖特定的状态代码。例如

$.ajax({
    ...
    error: function(jqXHR, textStatus, errorThrown) {
         if(jqXHR.status === 404){
             console.log('The requested unicorn is actually missing');
         }
    }
})
Run Code Online (Sandbox Code Playgroud)

现在,如果我如上所示执行,将显示两条消息

>The requested unicorn is actually missing
>Resource not found :O
Run Code Online (Sandbox Code Playgroud)

虽然我只是想获取The requested unicorn is actually missing消息。

global: false在单个 AJAX 调用设置中设置标志意味着忽略该 AJAX 调用中的所有全局 AJAX 函数,不幸的是,这对我的应用程序来说不是一个可行的解决方案。

任何的想法?谢谢!

Ara*_*yan 5

您可以执行以下操作

$.ajax({
    handleErrors: [404],
    ...
    error: function(jqXHR, textStatus, errorThrown) {
        if(jqXHR.status === 404){
            console.log('The requested unicorn is actually missing');
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

然后在您的全局处理程序中检查是否处理了错误

$(document).ajaxError(function(event, jqXHR, settings, thrownError) {
    if (settings.handleErrors && settings.handleErrors.indexOf(jqXHR.status) !== -1) {
        return;
    }
    switch (jqXHR.status) {
        case 403:
            console.log('Forbidden, go away!');
            break;
        case 404:
            console.log('Resource not found :O');
            break;
        case 422:
            console.log('Unprocessable entity.');
            break;
        case 500:
            console.log('Someone have to pay for this!');
            break;
        default:
            console.log('Anyone knows what is going on here?');
    }
});
Run Code Online (Sandbox Code Playgroud)