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

前端 未结 4 1777
攒了一身酷
攒了一身酷 2021-01-03 20:54

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 aut

4条回答
  •  一生所求
    2021-01-03 21:39

    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/

提交回复
热议问题