总结jQuery的$。阿贾克斯()方法来定义全局错误处理 [英] Wrap jQuery's $.ajax() method to define global error handling

查看:83
本文介绍了总结jQuery的$。阿贾克斯()方法来定义全局错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

妖异像<一个问题href="http://stackoverflow.com/questions/377644/jquery-ajax-error-handling-show-custom-exception-messages">this 之一,我在找换行jQuery的$。阿贾克斯()方法,这样我可以在一个位置,它然后将所有的应用程序的远程调用自动使用提供错误处理。

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.

最简单的方法是简单地创建一个新的名字,相似。获得如何$()和$。员额()实施立面$阿贾克斯()。不过,我希望能重新使用的名称$。阿贾克斯(),这样我们就可以使用标准的jQuery语法保持我们的code休息,从它藏身,我们已经增加了我们自己的错误处理的事实。这是实际的和/或良好的实现,也可能是可怕的想法?

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?

编辑:答复迄今表明.ajaxError()是要走的路。我知道这将捕获400和500级别的错误,但有什么办法(与此事件处理程序或其他方式),以赶上302重定向呢?我试图来处理重定向到登录页面的反应,但我们要拦截重定向时,它是一个XHR请求,允许用户取消迫使他们自动转发的作用吧。

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.

推荐答案

您可能想看看 $。 ajaxError

You might want to look at $.ajaxError.

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

jQuery提供一大堆其他的方式来连接全球处理器

要回答你的编辑,你可以赶上与 $成功的Ajax请求。的ajaxSuccess ,你可以捕获所有(成功的和失败的)与 $ .ajaxComplete 。您可以从该 XHR 参数,响应code像

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);
});

这篇关于总结jQuery的$。阿贾克斯()方法来定义全局错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆