深入理解AJAX系列第三篇--async属性值之同步和异步及同步和异步区别

来源:互联网 发布:eddie griffin 知乎 编辑:程序博客网 时间:2024/06/11 14:49

AJAX中根据async的值不同分为同步(async = false)和异步(async = true)两种执行方式;这个async这个属性,用于控制请求数据的方式,默认是true,即默认以异步的方式请求数据。
一、async值为false (同步)
顺序处理,当执行当前AJAX的时候会停止执行后面的JS代码,直到AJAX执行完毕后时,才能继续执行后面的JS代码。

var xhr = new createXHR();xhr.open( "get", "example.php", false );xhr.send( null );if( xhr.status == 200 ){    alert( xhr.responseText );}

二、async值为true(异步)
并行处理,当我们向服务器发出一个请求时,在服务器没返回结果之前,我们还是可以执行其他操作。

var xhr = createXHR();xhr.onreadystatechange = function(){    if( xhr.readyState == 4 ){        if( ( xhr.status >= 200 && xhr.status < 300  ) || xhr.status == 304 ){            alert( xhr.responseText );        }else{            alert( "Request was unsuccessful:" + xhr.status );        }    }};xhr.open( "get", "example.php", true );xhr.send( null );

在异步时才可以用xmlHttpReq.onreadystatechange状态值!同步的情况下,js会等待请求返回,获取status。不需要onreadystatechange事件处理函数。而异步则需要onreadystatechange事件处理,且值为4再正确处理内容。