2016-04-26 123 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); 
    } 
);