[英]javascript global variable not accessible where it should be!
consider the code考虑代码
$(function(){
$.ajax({
url:'cartProcess.php',
data:{pname:prod, pqty:qty},
type:'GET',
dataType:'json',
success:function(json){
var k = eval(json);
var n = k[0].Name;
var q = k[0].Quantity;
var t = k[0].Total;
},
complete:{
$('input.newQty').live('change', function(){
alert(t/q);
});
}
});
});
firebug gives an error saying t is not defined. firebug 给出一个错误,说 t 未定义。 How do i use these variables globally?
我如何在全局范围内使用这些变量?
This should do the trick:这应该可以解决问题:
$(function(){
var q = 0;
var t = 0;
$.ajax({
url:'cartProcess.php',
data:{pname:prod, pqty:qty},
type:'GET',
dataType:'json',
success:function(json){
var k = eval(json);
var n = k[0].Name;
q = k[0].Quantity;
t = k[0].Total;
},
complete:{
$('input.newQty').live('change', function(){
alert(t/q);
});
}
});
});
Javascript variables are always in the scope of the function they are declared in. As far as the complete function is concerned, t does not exist. Javascript variables are always in the scope of the function they are declared in. As far as the complete function is concerned, t does not exist.
You have this variable in two different scopes.您在两个不同的范围内拥有此变量。 change it like this
像这样改变它
$(function(){
var k ,t;
$.ajax({
url:'cartProcess.php',
data:{pname:prod, pqty:qty},
type:'GET',
dataType:'json',
success:function(json){
k = eval(json);
var n = k[0].Name;
var q = k[0].Quantity;
t = k[0].Total;
},
complete:{
$('input.newQty').live('change', function(){
alert(t/q);
});
}
});
});
You're defining the local variable t
inside the success
function - it will not be visible in the complete
function.您正在
success
的 function 中定义局部变量t
- 它在complete
的 function 中不可见。 Try defining them inside the "root" function before the $.ajax(...)
.尝试在
$.ajax(...)
之前的“根” function 中定义它们。
Your variables are local to your success function.您的变量是您成功 function 的本地变量。 You should move your
.live
code into the success function most probably.你应该将你的
.live
代码移动到成功的 function 中。
Also you don't need:你也不需要:
eval(json);
You've already set the dataType as json, so it should automatically be available as a json object.您已经将 dataType 设置为 json,因此它应该自动以 json object 的形式提供。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.