开发者

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 define开发者_JS百科d. 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.


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. Try defining them inside the "root" function before the $.ajax(...).


Your variables are local to your success function. You should move your .live code into the success function most probably.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜