jquery中ajax方法有个属性async用于控制同步和异步,默认是true,即ajax请求默认是异步请求,有时项目中会用到AJAX同步。这个同步的意思是当JS代码加载到当前AJAX的时候会把页面里所有的代码停止加载,页面出现假死状态,当这个AJAX执行完毕后才会继续运行其他代码页面假死状态解除。而异步则这个AJAX代码运行中的时候其他代码一样可以运行。
ajax中async这个属性,用于控制请求数据的方式,默认是true,即默认以异步的方式请求数据。
一、async值为true (异步)
当ajax发送请求后,在等待server端返回的这个过程中,前台会继续 执行ajax块后面的脚本,直到server端返回正确的结果才会去执行success,也就是说这时候执行的是两个线程,ajax块发出请求后一个线程 和ajax块后面的脚本(另一个线程)
例如
$.ajax({
type: "POST",
url: "Venue.aspx?act=init",
dataType: "html",
success: function(result) { //function1()
f1();
f2();
},
failure: function(result) {
alert('Failed');
}
})
function2();
在上例中,当ajax块发出请求后,他将停留function1(),等待server端的返回,但同时(在这个等待过程中),前台会去执行function2()。
异步的执行流程如下图所示:
二、async值为false (同步)
当执行当前AJAX的时候会停止执行后面的JS代码,直到AJAX执行完毕后时,才能继续执行后面的JS代码。
例如
$.ajax({
type:"POST",
url:"Venue.aspx?act=init",
dataType:"html",
async: false,
success:function(result){ //function1()
f1();
f2();
}
failure:function (result) {
alert('Failed');
},
} )
function2();
当把asyn设为false时,这时ajax的请求时同步的,也就是说,这个时候ajax块发出请求后,他会等待在function1()这个地方,不会去执行function2(),直到function1()部分执行完毕。
同步执行如图所示: