简体   繁体   中英

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM