jQuery: Handle fallback for failed AJAX Request

后端 未结 5 1740
傲寒
傲寒 2020-12-05 09:52

Can jQuery provide a fallback for failed AJAX calls? This is my try:

function update() {
    var requestOK = false;

    $.getJSON(url, function(){
        a         


        
相关标签:
5条回答
  • 2020-12-05 10:06

    You will need to either use the lower level $.ajax call, or the ajaxError function. Here it is with the $.ajax method:

    function update() {
      $.ajax({
        type: 'GET',
        dataType: 'json',
        url: url,
        timeout: 5000,
        success: function(data, textStatus ){
           alert('request successful');
        },
        fail: function(xhr, textStatus, errorThrown){
           alert('request failed');
        }
      });
    }
    

    EDIT I added a timeout to the $.ajax call and set it to five seconds.

    0 讨论(0)
  • 2020-12-05 10:09

    I believe that what you are looking for is error option for the jquery ajax object

    getJSON is a wrapper to the $.ajax object, but it doesn't provide you with access to the error option.

    EDIT: dcneiner has given a good example of the code you would need to use. (Even before I could post my reply)

    0 讨论(0)
  • 2020-12-05 10:11

    Dougs answer is correct, but you actually can use $.getJSON and catch errors (not having to use $.ajax). Just chain the getJSON call with a call to the fail function:

    $.getJSON('/foo/bar.json')
        .done(function() { alert('request successful'); })
        .fail(function() { alert('request failed'); });
    

    Live demo: http://jsfiddle.net/NLDYf/5/

    This behavior is part of the jQuery.Deferred interface.
    Basically it allows you to attach events to an asynchronous action after you call that action, which means you don't have to pass the event function to the action.

    Read more about jQuery.Deferred here: http://api.jquery.com/category/deferred-object/

    0 讨论(0)
  • 2020-12-05 10:14

    Yes, it's built in to jQuery. See the docs at jquery documentation.

    ajaxError may be what you want.

    0 讨论(0)
  • 2020-12-05 10:17

    I prefer to this approach because you can return the promise and use .then(successFunction, failFunction); anywhere you need to.

    var promise = $.ajax({
        type: 'GET',
        dataType: 'json',
        url: url,
        timeout: 5000
      }).then(function( data, textStatus, jqXHR ) {
        alert('request successful');
      }, function( jqXHR, textStatus, errorThrown ) {
        alert('request failed');
    });
    
    //also access the success and fail using variable
    promise.then(successFunction, failFunction);
    
    0 讨论(0)
提交回复
热议问题