A brief analysis of the reason why global variables cannot be assigned in asynchronous call methods of jquery ajax and the solution

  • 2020-03-30 01:16:47
  • OfStack

When we call a jquery ajax method, we sometimes need the method to return a value or assign a value to a global variable, but we find that the program does not get the value we want after execution, which is probably because you are using the asynchronous call async:true of ajax (default), such as:


function ManageCommentText(text) {
var result = text;
$.ajax({
data: "get",
url: "GetComments.aspx",
data: "type=getText&commentText=" + text,
cache: false,
async: false,
success: function (data) {
result = data;
}
})
return result;

The above method is a synchronous call to ajax, and the result completes the call to the method only after the data value is obtained and assigned to result. If set to async: true,
The result is returned without waiting to get the data value.

Another solution is to write your code directly to the success method. Not all of them can be written directly to success, depending on your business.

Note: if set to async: false, you lose the advantage of ajax asynchrony.


Related articles: