包装 jQuery 的 $.ajax() 方法来定义全局错误处理

发布于 2024-10-05 08:48:49 字数 533 浏览 3 评论 0原文

从像这个问题这样的问题分支出来,我正在寻找包装 jQuery 的 $.ajax() 方法,以便我可以在一个位置提供错误处理,然后应用程序的所有远程调用都会自动使用该错误处理。

简单的方法是简单地创建一个新名称,类似于 $.get() 和 $.post() 如何实现 $.ajax() 的外观。然而,我希望重用名称 $.ajax(),这样我们就可以使用标准 jQuery 语法保留其余代码,从而隐藏我们添加了自己的错误处理的事实。这是实用的和/或好实现的,还是可能是一个可怕的想法?

编辑:到目前为止的响应表明 .ajaxError() 是可行的方法。我知道这会捕获 400 和 500 级别的错误,但是有没有办法(使用此事件处理程序或其他方式)捕获 302 重定向?我正在尝试处理重定向到登录页面的响应,但我们希望在 XHR 请求时拦截该重定向,从而允许用户取消操作而不是强制它们自动转发。

Branching off of questions like this one, I'm looking to wrap jQuery's $.ajax() method such that I can provide error handling in one location, which would then be used automatically by all of an application's remote calls.

The simple approach would be to simply create a new name, similar to how $.get() and $.post() implement facades to $.ajax(). However, I'm hoping to reuse the name $.ajax(), such that we can keep the rest of our code using the standard jQuery syntax, hiding from it the fact that we've added our own error handling. Is this practical and/or good to achieve, or possibly a horrible idea?

EDIT: The responses so far indicate .ajaxError() is the way to go. I know this will catch 400 and 500 level errors, but is there a way (with this event handler or otherwise) to catch 302 redirects as well? I'm trying to handle responses that are redirecting to a login page, but we want to intercept that redirect when it's an XHR request, allowing the user to cancel the action instead of forcing them forwards automatically.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

我早已燃尽 2024-10-12 08:48:49

您可能需要查看 $.ajaxError

$(document).ajaxError(function myErrorHandler(event, xhr, ajaxOptions, thrownError) {
  alert("There was an ajax error!");
});

jQuery 提供一大堆附加全局处理程序的其他方法

要回答您的编辑,您可以使用 $.ajaxSuccess 捕获成功的 ajax 请求,并且可以使用 $.ajaxComplete 捕获所有(成功和失败)。您可以从xhr参数中获取响应代码,例如

$(document).ajaxComplete(function myErrorHandler(event, xhr, ajaxOptions, thrownError) {
  alert("Ajax request completed with response code " + xhr.status);
});

You might want to look at $.ajaxError.

$(document).ajaxError(function myErrorHandler(event, xhr, ajaxOptions, thrownError) {
  alert("There was an ajax error!");
});

jQuery provides a whole bunch of other ways to attach global handlers.

To answer your edit, you can catch successful ajax requests with $.ajaxSuccess, and you can catch all (successful and failed) with $.ajaxComplete. You can obtain the response code from the xhr parameter, like

$(document).ajaxComplete(function myErrorHandler(event, xhr, ajaxOptions, thrownError) {
  alert("Ajax request completed with response code " + xhr.status);
});
海未深 2024-10-12 08:48:49

jQuery 有一个名为 $.ajaxSetup() 的便捷方法,它允许您设置适用于其后的所有基于 jQuery 的 AJAX 请求的选项。通过将此方法放置在主文档就绪函数中,所有设置将自动应用于其余函数并在一个位置

$(function () {
    //setup ajax error handling
    $.ajaxSetup({
        error: function (x, status, error) {
            if (x.status == 403) {
                alert("Sorry, your session has expired. Please login again to continue");
                window.location.href ="/Account/Login";
            }
            else {
                alert("An error occurred: " + status + "nError: " + error);
            }
        }
    });
});

参考:https://cypressnorth.com/programming/global-ajax-error-handling-with-jquery/

jQuery has a handy method called $.ajaxSetup() which allows you to set options that apply to all jQuery based AJAX requests that come after it. By placing this method in your main document ready function, all of the settings will be applied to the rest of your functions automatically and in one location

$(function () {
    //setup ajax error handling
    $.ajaxSetup({
        error: function (x, status, error) {
            if (x.status == 403) {
                alert("Sorry, your session has expired. Please login again to continue");
                window.location.href ="/Account/Login";
            }
            else {
                alert("An error occurred: " + status + "nError: " + error);
            }
        }
    });
});

Reference: https://cypressnorth.com/programming/global-ajax-error-handling-with-jquery/

扬花落满肩 2024-10-12 08:48:49

实际上,jQuery 提供了钩子 .ajaxError() 就是为了这个目的。当来自页面的 ajax 请求完成但出现错误时,将调用您使用 $ajaxError() 绑定的所有处理程序。指定选择器允许您在 .ajaxError() 处理程序内引用 this

要使用它来处理页面上的所有 ajax 请求错误并使用 this 指向 document,您可以执行以下操作:

$(document).ajaxError(function(event, request, settings){
   alert("Error requesting page: " + settings.url);
});

Actually, jQuery provides the hook, .ajaxError() just for this purpose. Any and all handlers you've bound with $ajaxError() will be called when an ajax request from page completes with an error. Specifying a selector allows you to reference this inside of your .ajaxError() handler.

To use it to handle all ajax request errors on the page and use this to point to document, you could do something like this:

$(document).ajaxError(function(event, request, settings){
   alert("Error requesting page: " + settings.url);
});
So要识趣 2024-10-12 08:48:49

在某些情况下,您可能希望在调用本地错误处理函数之前进行全局错误处理。

像本示例中那样使用 $.ajaxPrefilter 是最佳解决方案我:

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
    let error = options.error;
    options.error = function (jqXHR, textStatus, errorThrown) {
        // global error handling first
        console.log('global ajax error');
        
        // override local error handling if exists
        if ($.isFunction(error)) {
            return $.proxy(error, this)(jqXHR, textStatus, errorThrown);
        }
    };
});

In some cases you might want to do global error handling before your local error handling function gets called.

Using $.ajaxPrefilter like in this example was the best solution for me:

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
    let error = options.error;
    options.error = function (jqXHR, textStatus, errorThrown) {
        // global error handling first
        console.log('global ajax error');
        
        // override local error handling if exists
        if ($.isFunction(error)) {
            return $.proxy(error, this)(jqXHR, textStatus, errorThrown);
        }
    };
});
国际总奸 2024-10-12 08:48:49

我认为这是一个坏主意。我认为包装 $.ajax 很好,但你正在谈论重新定义它。任何没有意识到这一点的人都会得到意想不到的结果。

正如其他人提到的,将处理程序绑定到 $.ajaxError 是正确的方法。

I think it's a bad idea. I think wrapping $.ajax is fine, but you're talking about re-defining it. Anyone who doesn't realize this will get unexpected results.

As others have mentioned, binding a handler to $.ajaxError is the way to go.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文