2012-11-21 38 views
1

在我的網頁中有2個部分需要單獨的AJAX調用,然後在將內容注入到DOM之前進行數據模板化。現在我正在研究這樣做的最佳方式,並且我一直在閱讀大量關於jQuery Deferreds的文章,這麼多關於我並不完全確定最佳方式的文章。下面是我認爲我會使用的代碼,但我會非常感激一些輸入。如果有人想爲此添加一些建議,我對緩存也很朦朧。通過我的AJAX調用獲取關於如何使用jQuery Deferreds的問題

JS

function ajaxCall1() { 
    var dfd = $.Deferred(); 
    return $.ajax({ 
     type: 'POST', 
     dataType: 'json', 
     url: '/url1', 
     data: { }, 
     success: function(data) { 
      // Run templating code 
     } 
    }); 
    return dfd.promise(); 
} 

function ajaxCall2() { 
    var dfd = $.Deferred(); 
    return $.ajax({ 
     type: 'POST', 
     dataType: 'json', 
     url: '/url2', 
     data: { }, 
     success: function(response) { 
      // Run templating code 
     } 
    }); 
    return dfd.promise(); 
} 

$.when(ajaxCall1(), ajaxCall2()) 
    .then(function(){ 
     // Display DOM elements 
    }) 
    .fail(function(){ 
     // Display error message 
    }); 
+0

您是否試過該代碼?發生了什麼? –

回答

1

爲了與Deferreds工作,你應該在

function ajaxCall1() { 
    var dfd = new $.Deferred(); 
    $.ajax({ 
     ... 
     success: function(data) { 
     dfd.resolve(data); 
     } 
    }); 
    return dfd.promise(); 
} 

function ajaxCall2() { 
    var dfd = new $.Deferred(); 
    $.ajax({ 
     ... 
     success: function(data) { 
     dfd.resolve(data); 
     } 
    }); 
    return dfd.promise(); 
} 

$.when(ajaxCall1(), ajaxCall2()).then(function(data1, data2) { 
    // data1 holds the result of the first ajax call, data2 that of the second call 
}); 

編輯的行

1 - generate a new $.Deferred() 
2 - return its .promise() from the function 
3 - .resolve() the deferred in the callback of the Ajax request 

東西:既然$。阿賈克斯()已經返回推遲,你可以這樣做,就像

function ajaxCall1() { 
    return $.ajax({ 
     ... 
    }); 
} 

function ajaxCall2() { 
    return $.ajax({ 
     ... 
    }); 
} 

$.when(ajaxCall1(), ajaxCall2()).done(function(data1, data2) { 
    // data1 holds the result of the first ajax call, data2 that of the second call 
}); 
+0

啊好的,所以從$ .When裏面我模板data1和data2然後做我的注射等從那裏? – styler

+0

試試吧,應該可以工作 – devnull69

+0

'$ .ajax()'默認已經返回'Deferred'。 –