在ajax的实例化对象中有个readyState属性,存储的就是Ajax状态码,但是这个状态码是不断变化的,因此如果我们直接在send方法后面打印readyState的话是看不到任何变化的,因此Ajax对象为我们提供了一个onreadystatechange事件。
前端部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
let xhr = new XMLHttpRequest();
//0 已经创建了ajax对象,但是还没有对ajax对象进行配置
console.log(xhr.readyState);
xhr.open('get', 'http://localhost:3000/readystate');
console.log(xhr.readyState);
// 当ajax状态码发生变化的时候触发
xhr.onreadystatechange = function () {
//2.请求已经发送了
//3. 已经接收到服务器端的部分数据了
//4. 服务器端的响应数据已经接收完成
console.log(xhr.readyState);
//对ajax状态码进行判断
//如果状态码的值为4代表数据已经接收完成了1
if (xhr.readyState===4){
console.log(xhr.responseText)
}
};
xhr.send();
</script>
</body>
</html>
node.js部分:
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.get('/readystate',(req,res)=>{
res.send('hello')
});
app.listen(3000);
console.log('服务器运行成功');