saber酱的抱枕

Fly me to the moon

07/26
11:30
学习

原生Ajax的简单实例

因为JavaScript水平太渣,以前我都是用JQuery来做ajax。现在看了些资料,感觉原生的写法也不难,而且兼容性也已经不错了,所以跟着练一练。

同步的ajax请求:

var xhr=new XMLHttpRequest();
xhr.open("get","http://saber.我爱你/demo/checknew.php",false);
xhr.send(null);
if (xhr.status===200) {
	alert(xhr.responseText);
}else{
	alert("发生了异常,状态码为"+xhr.status+","+xhr.statusText);
}

返回的数据里有如下属性:
responseText:作为响应主体被返回的文本。
responseXML:如果响应的内容类型是"text/xml"或"application/xml",这个属性中将保存包含着响应数据的XML DOM 文档。
status:响应的HTTP 状态。
statusText:HTTP 状态的说明。


异步的ajax请求:

var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
	if (xhr.readyState===4) {
		if (xhr.status===200) {
			alert(xhr.responseText);
		}else{
			alert("发生了异常,状态码为"+xhr.status+","+xhr.statusText);
		}
	}
}
xhr.open("get","http://saber.我爱你/demo/checknew.php",true);
xhr.send(null);

检测状态的部分也可以这样写:

xhr.onload=function (argument) {
	if (this.status == 200) {
		//……
    }
}

异步请求除了在xhr.open里将最后的参数设置为true之外,在接收数据时也和同步请求不同。异步请求通过检查xhr对象的readyState属性来判断请求处在哪个阶段。当readyState为4时,表示接收到了数据,并且数据可用。

我们通过onreadystatechange事件来检测readyState的值,当值为4时即可对数据进行处理。

另外,在接收到响应之前还可以调用abort()方法来取消异步请求。即xhr.abort(); 。

原生Ajax的简单实例