jquery Ajax Success Function Asynchronous Call method cannot assign a value to a global variable cause and solution
When calling 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 when it finishes executing, it is likely because you are using AJAX asynchronous call Async:true (by 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 invocation of Ajax, and only the call to result completion of the method is returned when the data value is obtained and assigned to result. If set to Async:true, the result is returned without waiting for the data value to be obtained.
Another solution is to write your code directly into the success method. (According to your business, not all of them can be written directly into the success.)
Note: If set to Async:false, you lose the advantage of Ajax Async.