Wrap jQuery's $.ajax() method to define global error handling

折月煮酒 提交于 2019-11-29 05:31:21
sje397

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

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

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/

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!