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; //Note that you cannot add the var keyword to the front
}
})
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.)
jquery Ajax Success Function Asynchronous Call method cannot assign a value to a global variable cause and solution