Let's look at the following code:
var flag=true;
var index=0;
$.ajax ({
URL: "http://www.jb51.net/",
success:function (data) {
flag=false;
}
});
while (flag) {
index++
}
alert (index);
What is the result of the index of the last alert, please?
Maybe someone will say 0 Bai. Actually, it's not that simple. We can try it by ourselves. You can see the final program entering a dead loop! How could that be?
We're looking at a piece of code:
var flag=true;
$.ajax ({
URL: "http://www.jb51.net/",
success:function (data) {
flag=false;
}
});
alert (flag);
What is the value of flag at the end of alert? Yes, it's true!. Why, then? When we succeeded in the AJAX request to set the flag to false, how is it true? This is actually the result of an AJAX asynchronous mechanism.
Explain here, synchronous and asynchronous. JS is a single thread, because the implementation of AJAX requests will consume a certain amount of time, even if there is a network failure and delay to return results; At this point, if synchronized execution, you must wait until the Ajax return results to execute the next code, if the AJAX request requires 1 minutes, the program will have to wait 1 minutes. If you're doing it asynchronously, you're telling the Ajax code. "Dude, since you're not returning the results, I'm going to wait for you, and I have a whole bunch of code to execute, so just tell me when you're done."
Ajax is asynchronously requested by default, so there is the result that we see above. That is, the code inside the Ajax is not finished, the following code is executed first.
So how do you get Ajax to execute a sync request? This requires setting up the async.
The code is as follows:
var flag=true;
var index=0;
$.ajax ({
URL: "http://www.jb51.net/",
Async:false,
success:function (data) {
flag=false;
}
}); While
(flag) {
index++
}
alert (index);
Async default is True, that is, asynchronous, we set to false, that is, synchronization. Let's take a look at the results then.
The above is small series for everyone to talk about JS Ajax asynchronous and synchronous request all the content of the problem, I hope that we support cloud-Habitat Community ~