Home  >  Article  >  Web Front-end  >  Detailed explanation of ajax async synchronization and asynchronousness in jQuery_jquery

Detailed explanation of ajax async synchronization and asynchronousness in jQuery_jquery

WBOY
WBOYOriginal
2016-05-16 15:37:351402browse

There is such a requirement in the project, use ajax to load data, return the page and assign a value, and then take out the value on the front end

This involves the order of the code. Sometimes the background has not returned the data, but the subsequent code has been executed.

So the value cannot be obtained

$.ajax({ type: "post",  url: "admin/PfmOptionRuleItem.do", success: function(data){  $("#ruleItem").val(data.ruleItem); //① } }); return $("#ruleItem").val(); //②

If ① has not returned data from the background, the value cannot be obtained if ② is executed at this time

The first letter of Ajax is the first letter of asynchronous, which means that all operations are parallel, and the order of completion has no relationship.

The async parameter of $.ajax() is always set to true, which indicates that other code can still be executed after the request starts.

If this option is set to false, this means that all requests are no longer asynchronous, which will also cause the browser to lock up.

Although the official does not recommend doing this, you just can’t use it too much, otherwise it will cause a poor user experience

Give me a chestnut

alert("setp 1"); $.ajax({  url: "admin/PfmOptionRuleItem.do",  async: false,  success: function(data){   alert("hello ajax"); //①  } }); alert("setp 2"); //②

When asyn is set to false, the ajax request is synchronized. That is to say, after the ajax block sends the request at this time,

He will wait at ① and will not execute ② until ① is completed

At this time, the order of execution is

setp 1

hello ajax

setp 2

If async is true, the execution order is

setp 1

setp 2

hello ajax

About the ajax async synchronization and asynchronousness in jQuery described in this article, I have introduced them all. I hope it will be helpful to everyone.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn