简体   繁体   中英

Unable to update parent functions variable from inside $.ajax call

I am trying to push a value that is being returned inside the ajax call to an array outside of the call, but still inside the parent function. It seems that I am not able to access any variable and update it from inside the ajax success statement. Thanks in advance for the help.

     var bill = [];
     var billDate = [];
     $(document).ready(function(){
       $.ajax({
         url: '../Js/readData.php',
         data: "",
         dataType: 'json',
         success: function(data)
         {
           //var obj=JSON.parse(data);
           var obj=data;
           for (var x in obj)
             {
               bill.push(obj[x].Amount);
               billDate.push(obj[x].Dates);
             }
         }
      });

The ajax call is asynchronous so the variables are not updated immediately for availability outside of the success function. It is called after the time involved with loading the data from the server.

You may want to move the anonymous success function to an external function and do whatever handling you need in there.

 $(document).ready(function(){ $.ajax({ url: '../Js/readData.php', data: "", dataType: 'json', success: mySuccessFunction }); var mySuccessFunction = function(obj) { for (var x in obj) { bill.push(obj[x].Amount); billDate.push(obj[x].Dates); } } 

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