Home >Web Front-end >JS Tutorial >Break down the differences between async:false and async:true in Ajax requests
Below I will bring you an article detailing the differences between async:false and async:true in Ajax requests. Let me share it with you now and give it as a reference for everyone.
The example is as follows:
function test(){ var temp="00"; $.ajax({ async: false, type : "GET", url : 'userL_checkPhone.do', complete: function(msg){ alert('complete'); }, success : function(data) { alert('success'); temp=data; temp="aa"; } }); alert(temp); }
checkPhone() method in UserLAction
public void checkPhone() throws IOException { this.getServletResponse().setContentType("text/html; charset=UTF-8"); this.getServletResponse().setHeader("Cache-Control", "no-cache"); PrintWriter out = this.getServletResponse().getWriter(); out.print("true"); }
async: false, (default is true);
When async: false is synchronous, the Ajax request in this test() method locks the entire browser,
Only userL_checkPhone Only after the execution of .do is completed, other operations can be performed.
So the execution result is first alert('success'); alert('complete'); alert("aa");
When async: true, the ajax request is asynchronous. But there is a problem: the ajax request in test() and the subsequent operations are executed asynchronously, so when userL_checkPhone.do has not yet been executed, the operations following the ajax request may have been executed,
So the result is alert('success'); alert('complete'); alert("00");
In this way, you will find that alert("success") and alert(temp) are executed almost simultaneously. So temp is the initialized value temp = "00", not temp="aa";
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Ajax and mysql data interaction to create a message board function
Ajax synchronization and asynchronous problem analysis and solutions
Instances of ajax responding to json strings and json arrays (graphic tutorial)
The above is the detailed content of Break down the differences between async:false and async:true in Ajax requests. For more information, please follow other related articles on the PHP Chinese website!