2010-11-30 51 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