fre*_*est 1 javascript variables jquery scope
我有以下javascript:
$.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 );
Run Code Online (Sandbox Code Playgroud)
问题是,这两个变量moulding_1_cost,并moulding_1_width在该电话的getJSON以外的不确定.如何在getJSON调用之外使这两个变量可用?
在回调运行之前(当服务器返回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 );
});
Run Code Online (Sandbox Code Playgroud)
或者调用另一个这样的函数:
$.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 );
}
Run Code Online (Sandbox Code Playgroud)
在任何一种情况下,一旦你拥有数据,你需要触发任何使用数据,所有异步操作都是这样的.