<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<script>
/* 学习目标:XMLHttpRequest的两个事件
1. onload事件 : 接收服务器响应的数(一次请求,只会执行一次)
2. onreadystatechang事件 : 作用与onload事件一致(一次请求,会执行多次)
面试点: XMLHttpRequest对象的状态码 (xhr.readyState)
0: 请求未建立 (创建了xhr对象,但是还没调用open)
1: 服务器连接已建立
2. 请求已接收 (send之后,服务器已经接收了请求)
3. 请求处理中
4. 请求已完成,且响应已就绪 ( 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)
}
}
</script>
</body>
</html>
XMLHTTPRequest状态码
最新推荐文章于 2023-07-20 08:59:14 发布