2010-11-30 13 views
1

私は、次のJavaScriptを持っている:jQueryの - 変数のスコープ問題

 $.getJSON('/calculate_quote/' + moulding_1_id, function(data) { 
     moulding_1_cost = data.moulding.cost; 
     moulding_1_width = data.moulding.width; 
     }); 
     cost_of_moulding = ((2 * (width + (2 * moulding_1_width)) + 2 * (height + (2 * moulding_1_width)))/1000) * moulding_1_cost; 
     $('#item_total').html(cost_of_moulding); 

問題は二つの変数moulding_1_costmoulding_1_widthがgetJSON呼び出しの外で未定義されていることです。 getJSON呼び出しの外部でこれら2つの変数を使用できるようにするにはどうすればよいですか? (サーバはJSONデータで戻ってくるとき)

答えて

7

変数はではありませんが、あなたがこのように、そのコールバックからそれらを使用するものは何でもコードを呼び出す必要があるので、そのコールバックが実行されるまでを設定します。

$.getJSON('/calculate_quote/' + moulding_1_id, function(data) { 
    var moulding_1_cost = data.moulding.cost; 
    var moulding_1_width = data.moulding.width; 
    var cost_of_moulding = ((2 * (width + (2 * moulding_1_width)) + 2 * (height + (2 * moulding_1_width)))/1000) * moulding_1_cost; 
    $('#item_total').html(cost_of_moulding); 
}); 
このような

または電話で別の関数:いずれの場合も

$.getJSON('/calculate_quote/' + moulding_1_id, function(data) { 
    someFunction(data.moulding.cost, data.moulding.width); 
}); 
function someFunction(mqc, m1w) { 
    var cost_of_moulding = ((2 * (width + (2 * m1w)) + 2 * (height + (2 * m1w)))/1000) * m1c; 
    $('#item_total').html(cost_of_moulding); 
} 

真残るものは、あなたがデータを持っていたら、データを使用して何でもトリガする必要があり、すべての非同期操作はこのようなものです。 )

+0

またはこれ以上^ – slobodan

-2

var moulding_1_cost; 
var moulding_1_width; 

任意のJavaScript関数の外側に追加します。

+0

これは、コールバックの前に '$ .getJSON'の後の数式が実行されるため、問題を引き起こします。 – Stephen

0

あなたはそれが正しい順序で起こることを確実にするためにgetJSONコール内ですべてをやるべき。

0

実際には(コード実行後の)定義されていません。 varキーワードをスキップすると、それらの名前はグローバルスコープ(ほとんどの場合は.. window)に直接移動します。したがって、このスクリプトが実行されると、スクリプトのどこからでもwindow.moulding_1_costにアクセスできます。

ここで問題が発生する可能性が最も高いです。これはajax requestの成功ハンドラであるため、このコードは非同期で実行されるため、即座に実行されることはありません。

これを解決するには、自分でコールバック関数を使用することをお勧めします。 Nick Craverの答えはこれに関するかなり良いデモンストレーションをしています。

+0

..そして、私は理由がなければこれをdownvoting誰が好奇心だ。 – jAndy

+0

私のdownvoteではありませんが、実際には何かが作成されて初期化されない限り、実際には完全に 'undefined'です。コールバックが少なくとも1回は実行されるまで、まったく定義されません。 –

+0

@NickCraver:私はそれを述べましたか? – jAndy