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

前端 未结 4 1780
攒了一身酷
攒了一身酷 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:31

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

提交回复
热议问题