底层原理,实际开发时多使用Axios框架进行开发
一、工作流程
1、实例化ajax对象
XMLHttpRequest 对象用于在后台与服务器交换数据
<script>
//(1).实例化ajax对象
let xhr = new XMLHttpRequest()
</script>
2、设置请求方法和地址
使用XMLHttpRequest 对象的 open() 方法设置请求方法和地址
<script>
//(2).设置请求方法和地址
//get请求的数据直接添加在url的后面 格式是 url?key=value
xhr.open('get', '接口url')
</script>
3、发送请求 我们需要将请求发送到服务器,需要用到使用XMLHttpRequest 对象的 send() 方法
//(3).发送请求
xhr.send()
4、接收返回的数据用于数据渲染
//(4).注册回调函数
xhr.onload = function () {
console.log(xhr.responseText)
}
二、请求方法
请求方式 | 描述 | 特点 |
---|---|---|
post | 一般用于新增数据(提交数据) | 请求体传参 |
get | 一般用于查询数据(查询数据) | 请求行(url)传参 |
delete | 一般用于删除数据 | 请求体传参 |
put | 一般用于更新全部数据 | 请求体传参 |
patch | 一般用于更新局部数据 | 请求体传参 |
post方法与get方法的区别
1. 传参方式不同
get参数在请求行中发送(在url后面拼接)
post参数在请求体中发送
2. 数据大小不同
get有大小限制, 一般 2-5 MB
post没有大小限制 (文件上传)
3. 传输速度不同
get传输速度快
post传输速度慢
4. 安全性不同
get安全性低
post安全性高 (登录、注册必须是post请求)
三、XMLHttpRquest对象两个事件及其执行流程
1、xhr.onload :
服务器响应数据执行(一次请求,一次执行)
<script>
//(1).实例化ajax对象
let xhr = new XMLHttpRequest()
//(2).设置请求方法和地址
xhr.open('get', 'http://wthrcdn.etouch.cn/WeatherApi?city=武汉')
//(3).发送请求
xhr.send()
//(4).接收数据
xhr.onload = function() {
console.log(xhr)
}
</script>
执行结果为:
2、xhr.onreadystatechange :
xhr请求状态变化会执行 ( 一次请求,会执行多次 )
<script>
//(1).实例化ajax对象
let xhr = new XMLHttpRequest()
//请求未初始化
console.log(xhr.readyState)//0
//(2).设置请求方法和地址(请求行)
xhr.open('post', 'http://www.liulongbin.top:3009/api/login')
//服务器连接已建立
console.log(xhr.readyState)//1
//(3).设置请求头(post请求才需要设置)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
//(4).发送请求 : 参数格式 'key=value'
xhr.send('username=admin&password=123456')
//(5).接收数据
xhr.onreadystatechange = function () {
console.log(xhr.readyState)//2 3 4
//当readyState为4,表示响应数据了
if (xhr.readyState == 4) {
console.log(xhr.response)
}
}
</script>
执行结果为:
0: 请求未初始化 (open之前)
1: 服务器连接已建立 (open之后)
2: 请求已接收 ( 服务器已经收到你的请求 )
3: 请求处理中 ( 服务器正在处理你的请求 )
4: 请求已完成,且响应已就绪 ( 服务器完成响应, onload事件就是在这里执行 )
————————————————————————————————————