Synchronous asynchronous problems brought by Ajax callback function Execution Order _ function

Source: Internet
Author: User

Let's look at a piece of code like this:

$ (function () {

var a =0;

$.getjson (

"Student_toadd",

{Stunum:10},

function (Json,status)
{
$.each (Json,function (i) {
$ (' #stuDiv '). Append ("<div> Student study Number:" +json[i].num+ "</div>");
}

.........................................

a = 10;
});

}
)

alert (a);

});

You can tell me what a pop-up a is.

I said: It could be 10, maybe 0.

because the execution of Ajax is asynchronous, it is possible that the callback function has not yet got the return value and then pops a.

Solutions

var a = 0;

$.ajax ({
Type: "Get",

DataType: "JSON",

Async:false//asynchronous to False

URL: "Student_toadd",

Data:{stunum:10},

         success:function (json,status)
                          {
                                   $.each ( Json,function (i) {
                                            $ (' #stuDiv '). Append ("<div> Student Study No.:" +json[i].num+ "< /div> ");
                                    }

.........................................

a = 10;
);
});

alert (a);

This means that the $.ajax will get the return value after executing JS. so A is 10. So what's the inspiration? For example we need to wait until the return value draws some elements on the page, and if it is asynchronous, it is possible to draw something that is empty.

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.