After we use JQuery’s Ajax to extract data from the background, we want to assign it to a global variable, but we can’t assign it. Why?
The reason is actually very simple. The Ajax we use is an asynchronous operation, which means that the data has not been extracted when you assign the value. Of course, you cannot assign it, so you only need to change it to a synchronous operation~
Method 1: Set up synchronization first and then perform Ajax operation
//在全局或某个需要的函数内设置Ajax异步为false,也就是同步 $.ajaxSetup({ async :false}); //然后再进行你的Ajax操作 $.post(地址,参数,function(data, status){if(status =="success"){//赋值给全局变量}else{ alert("wrong");}});
Method 2: Use $.ajax directly
$.ajax({ type :"post", url :地址, data :"参数"+参数的值, async :false, success :function(data){//赋值给全局变量;}});
Example code: