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.