Summary of methods and differences between synchronous and asynchronous processing in js
If you want to post-process the results returned by a request using an ajax request, it is best to use a synchronous request. The following describes the methods and differences between synchronous and asynchronous processing in js. Do not miss out if you are interested.
When an asynchronous request is used, it is sometimes necessary to return the result of the asynchronous request to another js function. In this case, the asynchronous request is not returned, the js function that sends the request has completed subsequent operations, that is, the return has been executed, which will result in the return result being a null character.
Conclusion: To send the returned results after processing the ajax request, it is best to use synchronous requests.
For example, in the following example, the returned result is incorrect because the ajax asynchronous request has not been executed and the function has already executed return,
The Code is as follows:
Function fn (){
Var result = "";
$. Ajax ({
Url: 'Your url ',
Data: {name: value },
Cache: false,
Async: true,
Type: "POST ",
Success: function (data ){
Do something ....
Result = ....
}
// Processing the data returned by ajax may also cause errors
Return result;
}
1 asynchronous request method:
The Code is as follows:
$. Ajax ({
Url: 'Your url ',
Data: {name: value },
Cache: false,
Async: true,
Type: "POST ",
DataType: 'json/xml/html ',
Success: function (result ){
Do something ....
}
});
2. synchronous Request Method
The Code is as follows:
$. Ajax ({
Url: 'Your url ',
Data: {name: value },
Cache: false,
Async: false,
Type: "POST ",
DataType: 'json/xml/html ',
Success: function (result ){
Do something ....
}
});