When calling a jquery ajax method, we sometimes need the method to return a value or assign a value to a global variable, but we find that the value we want is not obtained after the program is executed, for example:
var i=0;//定义一个全局全量 $.get(url,function(data){ i=9; })//然后调用jquery的一个函数 alert(i);//得到的是0而不是9
The data in data is obtained asynchronously. The code in the global environment is executed when the page is loaded. At this time, the asynchronous data acquisition has not been completed and the value cannot be obtained.
Solution:
var i=0; $.ajax({ url:url, success:function(){ i=9; }, async:false }); alert(i);
Or add it directly before $.get()
$.ajaxSettings.async = false;
Modify the default configuration.
The default setting value of async is true. In this case, it is an asynchronous method. That is to say, when ajax sends a request, while waiting for the server to return, the front desk will continue to execute the script after the ajax block until the server returns the correct result. Success will be executed only when success is executed, which means that two threads are executed at this time, one thread after the ajax block sends the request and the script behind the ajax block.
Of course, if it is set to async:false, the advantages of ajax asynchrony will be lost, and it needs to be treated differently depending on the situation.
HTTPS://blog.CSDN.net/JA tion_/article/details/49357307
HTTPS://wuwuwu.cn blog上.com/发-photo/fear/4424633.HTML
HTTPS://wuwuwu.basic51.net/article/45432.htm