xhr.readyState
代码测试
window.onload=function(){
var xhr=null;
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}else{
xhr=new ActiveXObject('Microsoft.XMLHTTP');
}
console.log("状态a:"+xhr.readyState);
xhr.open('get','new_file.php',true);
console.log("状态b:"+xhr.readyState);
xhr.send(null);
console.log("状态c:"+xhr.readyState);
xhr.onreadystatechange=function(){
console.log("状态d:"+xhr.readyState);
}
console.log("状态e:"+xhr.readyState);
}
测试结果
分析#
0:XMLHttpRequest对象创建完成
1:表示发送请求的动作准备好了,但是还没有开始发送
2:表示已经发送完成
3:服务器已经返回了数据
4:服务器返回的数据已经可以开始用了
xhr.status
xhr.onreadystatechange=function(){
//所以我们这里判断为4的时候数据才可以用
if(xhr.readyState==4){
if(xhr.status==200){
// xhr.status==200表示http请求成功
// status的值常见的有:
// 404:无法找到页面
// 503:服务器端有错误
}
}
console.log("状态d:"+xhr.readyState);
}