1. onload事件 : 接收服务器响应的数(一次请求,只会执行一次)
2. onreadystatechang事件 : 作用与onload事件一致(一次请求,会执行多次)
面试点: XMLHttpRequest对象的状态码 (xhr.readyState)
0: 请求未建立 (open之前)
1: 服务器连接已建立 (open之后)
2. 请求已接收 (send之后,服务器已经接收了请求)
3. 请求处理中
4. 请求已完成,且响应已就绪 (服务器完成响应,onload事件就是在这里执行)
//(1).实例化ajax对象
let xhr = new XMLHttpRequest()
console.log(xhr.readyState)
//(2).设置请求方法和地址
xhr.open("post", "http://www.liulongbin.top:3009/api/login")
//(3).设置请求头(post请求才需要设置)
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
console.log(xhr.readyState)
//(4).发送请求 : 参数格式 'key=value'
xhr.send("username=admin&password=123456")
//(5).注册回调函数
//a. onload 是新式浏览器才支持的
//b. 如果要兼容更早的浏览器,可以使用 onreadystatechange
//c. onreadystatechange触发时机 : xhr.readState状态变化
// xhr.onload = function() {};
xhr.onreadystatechange = function () {
console.log(xhr.readyState)
//onreadystatechange会触发多次,一般需要判断xhr.readState == 4 才获取响应数据
if (xhr.readyState == 4) {
console.log(xhr.responseText)
}
}