Can't access global variable in jQuery $.get within function

后端 未结 3 1804
甜味超标
甜味超标 2021-01-18 10:25

Below is some code I\'m having trouble with. Basically, I\'m defining an empty array as a global variable (var playlist = []) and then trying to add elements to it within a

相关标签:
3条回答
  • 2021-01-18 10:40

    Chances are, playlist is getting used before $.get returns - as ajax calls are asynchronous. It works within the success callback because that gets fired once the request has completed, so it will contain the data you expect.

    0 讨论(0)
  • 2021-01-18 10:45

    .get is asynchronous, hence the need to provide a callback function. While your get is still in process you are trying to use the array, probably before it's actually been populated.

    0 讨论(0)
  • 2021-01-18 11:00

    You don't have to do any of this. I ran into the same problem with my project. what you do is make a function call inside the on success callback to reset the global variable. As long as you got asynchronous javascript set to false it will work correctly. Here is my code. Hope it helps.

     var exists;
    
     //function to call inside ajax callback 
     function set_exists(x){
         exists = x;
     }
    
      $.ajax({
         url: "check_entity_name.php",
         type: "POST",
         async: false, // set to false so order of operations is correct
         data: {entity_name : entity},
         success: function(data){
         if(data == true){
            set_exists(true);
         }
         else{
            set_exists(false);
         }
      }
    });
    
    if(exists == true){
        return true; 
    }
    else{
        return false;
    }
    

    Hope this helps you .

    0 讨论(0)
提交回复
热议问题