jquery Ajax Success Function Asynchronous Call method cannot assign a value to a global variable cause and solution

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.