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

后端 未结 3 1805
甜味超标
甜味超标 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 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 .

提交回复
热议问题