jQuery: Handle fallback for failed AJAX Request

后端 未结 5 1756
傲寒
傲寒 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: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);
    

提交回复
热议问题