An analysis of the reasons why jquery Ajax can not assign values to global variables in the asynchronous invocation method _jquery

Source: Internet
Author: User

When invoking a jquery Ajax method, we sometimes need the method to return a value or assign a value to a global variable. But we found out that we didn't get the value we wanted when the program was done, and it's probably because you're using an AJAX asynchronous call Async:true (by default), Such as:

Copy Code code as follows:

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, which returns the call of result to complete the method only after the data value has been obtained and assigned to cause. 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 can be written directly into the success).

Note: If set to Async:false, the advantages of Ajax asynchronous are lost Oh.

Related Article

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.