When using asynchronous requests, sometimes it is necessary to return the result of the asynchronous request to another js function. In this case, the request result will not be returned until the asynchronous request is returned. The js function where the request is sent has completed the subsequent operations, that is, the return has been executed. , which will cause the return result to be a null character.
Summary: To process the results returned by a send request after using an ajax request, it is best to use a synchronous request.
For example: In the following example, the return result may be incorrect, because the ajax asynchronous request has not yet been executed and the function has already executed return.
Copy the code code 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 in ajax will also cause errors
return result ;
}
1 Asynchronous request method:
Copy the code code 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
Copy the code code as follows:
$.ajax({
url : 'your url',
data:{name:value},
cache: false,
async : false,
type: "POST",
dataType : 'json/xml/html',
success : function (result){
do something....
}
});