2013-06-03 89 views
1

如何確保調用回調代碼。如何確保調用jquery的回調

確保回調到達gotMinPremium或gotMaxPremium檢查之前。

我不想使用setTimeOut函數。

setTimeOut函數使腳本始終運行。任何其他方法?

謝謝

回答

2

setTimeout不能正常工作,因爲調用setTimeout不會阻止一切後,從執行,它只是註冊的代碼塊在某個時候在今後運行和然後立即執行以下代碼setTimeout

使用延遲的對象,你可以同時啓動AJAX調用,並等待他們兩個繼續之前完成。

var getMin = $.post(...); 
var getMax = $.post(...); 

$.when(getMin, getMax).done(function(d1, d2) { 
    // d1 and d2 will contain the result of the two AJAX calls 
    MinPremium = d1.MinPremium; 
    MaxPremium = d2.MaxPremium; 

    ... 
}); 

注意,這將總是使雙方AJAX調用(使他們在平行或者:

$.post(...).done(function(data) { 
    minPremium = data.MinPremium; 

    // handle your minimum test here 
    ... 

    $.post(...).done(function(data) { 
     maxPremium = data.MaxPremium; 

     // handle maximum test here 
     ... 
    }); 
}); 

FWIW,沒有任何理由你不能有一個AJAX調用返回值?

+1

+1使用'$ .when'。甜! – Nikhil