下面我就为大家带来一篇细数ajax请求中的async:false和async:true的差异。现在就分享给大家,也给大家做个参考。
实例如下:
function test(){
var temp="00";
$.ajax({
async: false,
type : "get",
url : 'userl_checkphone.do',
complete: function(msg){
alert('complete');
},
success : function(data) {
alert('success');
temp=data;
temp="aa";
}
});
alert(temp);
}
userlaction中checkphone()方法
public void checkphone() throws ioexception {
this.getservletresponse().setcontenttype("text/html; charset=utf-8");
this.getservletresponse().setheader("cache-control", "no-cache");
printwriter out = this.getservletresponse().getwriter();
out.print("true");
}
async: false,(默认是true);
当async: false为同步,这个 test()方法中的ajax请求将整个浏览器锁死,
只有userl_checkphone.do执行结束后,才可以执行其它操作。
所以执行结果是先alert('success'); alert('complete'); alert(aa);
当async: true 时,ajax请求是异步的。但是其中有个问题:test()中的ajax请求和其后面的操作是异步执行的,那么当userl_checkphone.do还未执行完,就可能已经执行了 ajax请求后面的操作,
所以结果是alert('success'); alert('complete'); alert(00);
这样就会发现alert(success)和alert(temp)几乎是同步执行,所以temp就是初始化的值temp = 00,而不是 temp=aa;
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
ajax与mysql数据交互制作留言板功能
ajax同步和异步问题浅析及解决方法
ajax响应json字符串和json数组的实例(图文教程)
以上就是细数ajax请求中的async:false和async:true的差异的详细内容。