2010-11-30 54 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調用之外使這兩個變量可用?

回答

7

的變量沒有設置直到回調運行(當服務器重新使用JSON數據),所以你需要調用任何代碼使用它們從回調,像這樣:

$.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 2010-11-30 14:47:35

-2

添加

var moulding_1_cost; 
var moulding_1_width; 

之外的任何JavaScript函數;)

+0

這將導致一個問題,因爲'$ .getJSON`之後的數學計算將在回調之前執行。 – Stephen 2010-11-30 14:48:30

0

你應該做的getJSON調用內部的一切,以確保它發生在正確的順序。

0

Infact它們不是未定義的(代碼執行後)。通過跳過var關鍵字,這些名稱將直接進入全局範圍(在大多數情況下,它是window)。所以一旦這段腳本執行完畢,您可以從腳本的任何位置訪問window.moulding_1_cost

而這最有可能是你的問題在這裏,時機。由於這是ajax request的成功處理程序,因此此代碼異步運行,因此不會立即執行。

要解決這個問題,最好使用自己的回調函數。 Nick Craver的回答在這方面有很好的演示。

+0

..我很好奇,誰沒有理由地降低了這一點。 – jAndy 2010-11-30 14:51:00