开发者

AJAX error handling with jQuery: should I use $.ajaxSetup() or $.fn.ajaxError()

I want to alert the user whenever there's an AJAX error. You can do this via $.ajaxSetup:

$.ajaxSetup开发者_StackOverflow({ 
  error: function() {
    alert("OOPS!")
  }
});

But the jQuery docs recommend against this:

Note: Global callback functions should be set with their respective global Ajax event handler methods-.ajaxStart(), .ajaxStop(), .ajaxComplete(), .ajaxError(), .ajaxSuccess(), .ajaxSend()-rather than within the settings object for $.ajaxSetup().

So I guess I'm supposed to do this:

$("#some_random_div").ajaxError(function() {
  alert("OOPS!")
});

This doesn't make sense to me: the AJAX error callback pertains to my application as a whole, not a specific page element. So why should the callback function be associated with an individual page element?

So: why do the jQuery docs recommend using what looks like a less readable approach, and which approach is best?


The typical use is that the specific page element you bind ajaxError to is the div where your error message is going to be displayed; perhaps a "flash" message div at the top of your page. This way you have direct access to that div to append your message.

But if you're not using a particular DOM element as your message display area, you could certainly bind it to $(document) or some other such global element.


The docs state:

As of jQuery 1.8, the .ajaxError() method should only be attached to document.

http://api.jquery.com/ajaxError/


You can wire up the error function to the whole body like this:

$('body').ajaxError(function() {
    alert("OOPS!")
});


There may exist circumstances where it might relate to an individual control - such as when you have an autocomplete that round trips to the database via ajax, as opposed to an entire page like on a submit. This would then determine if you want to isolate the error on a component of the page and if so what the response to the error should be rather than with a more generic approach.


0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜