JQuery USES Ajax to assign values to global variable exceptions

  • 2020-03-30 01:16:50
  • OfStack

We used JQuery's Ajax to extract data from the background and tried to assign it to a global variable, but we couldn't. Why?

The reason is actually very simple, we use Ajax asynchronous operation, which means that when you assign the value of the data has not been extracted, of course, you can not assign, so just change to a synchronous operation ~

Method 1: set the synchronization first before performing the Ajax operation


//Set Ajax asynchrony to false, or synchronous, globally or within a required function
$.ajaxSetup({ 
    async : false 
});  
//Then proceed with your Ajax operations
$.post( address ,  parameter , function(data, status) { 
    if (status == "success") { 
        //Assign a value to a global variable
    } 
    else { 
        alert("wrong"); 
    } 
}); 

Method 2: use $.ajax directly

$.ajax({ 
    type : "post", 
    url : address , 
    data : " parameter " +  The value of the parameter , 
    async : false, 
    success : function(data){ 
        //Assign values to global variables;
     } 
}); 


Related articles: