2016-04-26 126 views
0

什麼是鏈接jQuery ajax請求的乾淨可讀的方式?我試圖擺脫這個回調地獄。我已經準備好了很多關於這方面的文章,但他們似乎沒有更復雜的回答。乾淨地鏈jQuery ajax請求

$.get('file1.php') 
    .done(function(data) { 
    $.get('file2.php') 
     .done(function(data) { 
     $.get('file3.php') 
      .done(function(data) { 

      }) 
      .fail(function() { 
      showError(); 
      }) 
     }) 
     .fail(function() { 
     showError(); 
     }) 
    }) 
    .fail(function() { 
    showError(); 
    }) 
+1

看看這個答案:http://stackoverflow.com/a/16045729/984275 – technophobia

回答

1

注意,通過jQuery的Ajax請求返回的jqXHR對象可以用then被鏈接:

$.get('file1.php').then(function() { 
    return $.get('file2.php'); 
}, showError).then(function() { 
    return $.get('file3.php'); 
}, showError).then(function() 
    ... 
}, showError); 
1

嘗試的jQuery $.deffered對象,你不僅可以使多個Ajax有效調用,也使它可鏈接。在這裏你去:

var deferred = $.Deferred(); 

function getData() { 

    var ajaxCall1 = $.get("file1.php", {}, null, 'jsonp'); 
    var ajaxCall2 = $.get("file2.php", {}, null, 'jsonp'); 
    var ajaxCall3 = $.get("file3.php", {}, null, 'jsonp'); 

    $.when(ajaxCall1, ajaxCall2, ajaxCall3) 
    .done(function (response1, response2, response3) { 
     // Your logic come here 
    }); 

    return deferred.promise(); 
} 

getData() 
.then(
    function() { 
     alert('Success'); 
    }, 
    function (response1, response2, response3) { 
     alert('Response1 :' + response1 
        + 'Response2 :' + response2 
        + 'Response3 :' + response3); 
    } 
);