2011-10-19 7 views
0

私は条件をチェックするようにコードを設定しており、その条件に基づいてajax呼び出しを実行してJSONオブジェクトを取得するか、または別の処理形式に進むことができます。処理後、if/elseステートメントで処理されたデータに基づいていくつかの処理を行います。jQuery - ".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関数に渡します。

関連する問題