Home > Article > Web Front-end > What is the difference between async:false and async:true in Ajax requests?
This time I will bring you the difference between async:false and async:true in Ajax requests. What are the precautions when using async:false and async:true in Ajax requests? The following is a practical case, let’s take a look.
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";I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website! Recommended reading:Ajax+mysql to create a message board function
Ajax steps to implement data paging query Detailed explanation
The above is the detailed content of What is the difference between async:false and async:true in Ajax requests?. For more information, please follow other related articles on the PHP Chinese website!