2011-10-19 37 views
0

我已經設置了一段代碼來檢查一個條件,並根據該條件執行ajax調用來獲取JSON對象,或繼續進行其他形式的處理。處理完後,我會根據if/else語句中處理的數據做一些事情。jQuery - 延遲if/else處理直到「.get」調用完成

但是我遇到了一個問題。代碼執行if/else,然後在.get完成處理之前繼續執行,因此我的最後一部分代碼無法正常工作。有沒有辦法延遲處理其餘代碼直到.get完成?

我的代碼的結構如下:

if(filename != undefined){ 
    $.get(filename, function(json){ 
    $.each(json, function(data){ 
     // Do stuff with the json 
    }); 
    }, "json"); 
} else { 
    // Do some other processing 
} 

// Do some additional processing based on the results from the if/else statement 
// This bit is getting processed before the .get has finished doing it's thing 
// Therefore there isn't anything for it to act upon 

回答

1

$.get使用async: false選項進行同步請求。 http://api.jquery.com/jQuery.ajax/

注:

@Neal: 「這並不總是最好的選擇,特別是如果Ajax請求掛起了太久。」

+0

@Kevin - 這並不總是最好的選擇。特別是如果ajax請求時間過長。 – Neal

+0

Thx Neal,那是真的。我會將其添加到答案中 – beefyhalo

3

做一個回調函數,而不是針對其他動作:

if(filename != undefined){ 
    $.get(filename, function(json){ 
    $.each(json, function(data){ 
     // Do stuff with the json 
     doTheRest(); 
    }); 
    }, "json"); 
} else { 
    // Do some other processing 
    doTheRest(); 
} 

function doTheRest(){ 

    // Do some additional processing based on the results from the if/else statement 

} 

只記得變量的作用域,如果你有,將參數傳遞給doTheRest函數。

相關問題