readyState属性和status属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="btn">按钮</button>
</body>
<script src="../9.2/创建XMLHTTPRequest对象.js"></script>
<!-- 引入写好的适配浏览器的创建XMLHTTPRequest对象 -->
<script>
var btn = document.getElementById('btn');
btn.addEventListener('click',function(){
var xhr = createXMLHttpRequest();
xhr.onreadystatechange = function(){
//监听通信状态
//XMLHTTPRequest对象的readyState属性 表示服务器的通信状态 值为0 1 2 3 4
//0是未初始化(得不到的状态) 就是没有调用open 1是open方法被调用(想要得到1就要在open之前) 2是send方法被调用
//3是正在返回、响应 4是响应完毕
console.log(xhr.status);
// if(xhr.readyState === 4){
// //访问的url是错误的也会有1 2 3 4
// //因此需要其他的保证措施
// //XMLHTTPRequest对象的status属性 用于得到当前请求之后的状态码(比如404等)
// //通过他就能知道url有没有问题
// console.log(xhr.status);
// if(xhr.status === 200){//200表示请求成功
// console.log(xhr.responseText);
// }
// }
if(xhr.readyState === 4 && xhr.status === 200){
//接收服务器响应结果
//responseText属性 专门接收字符串类型的数据内容
//responseXML属性 专门接收XML数据格式的结果内容
console.log(xhr.responseText);
}
}
xhr.open('get','http://127.0.0.1:1877/Ajax/%E4%BB%A3%E7%A0%81/9.2/02%E6%B5%8B%E8%AF%95XMLHttpRequest%E5%AF%B9%E8%B1%A1.html');
xhr.send(null);
//把这些接收到的结果更新到HTML页面上
})
</script>
</html>