一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

细数Ajax请求中的async:false和async:true的差异

时间:2017-03-27 编辑:简简单单 来源:一聚教程网

实例如下:

 代码如下复制代码

functiontest(){

  vartemp="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";

热门栏目