XMLHttpRequest是浏览器内置的一个构造函数
作用:基于 new 出来的 XMLHttpRequest 实例对象,可以发起 Ajax 的请求。
axios 中的 axios.get()、axios.post()、axios() 方法,都是基于 XMLHttpRequest(简称:XHR) 封装出来的!
使用 XMLHttpRequest 发起请求
我们可以不用 axios 封装的 Ajax 函数,直接基于 XMLHttpRequest 发起 Ajax 请求。
1、创建 xhr 对象
2、调用 xhr.open() 函数
3、调用 xhr.send() 函数
4、监听 load 事件
XMLHttpRequest 发起 GET请求 (不带参数)
// 准备对象
const xhr = new XMLHttpRequest()
// 准备数据: xhr.open(方式,地址,同步或异步 默认是异步)
xhr.open('get','http://ww.liulongbin.top:3009/api/get')
// 发送数据
xhr.send()
// 监听onload事件
xhr.addEventListener('load',function(){
console.log(xhr.response);
})
XMLHttpRequest 发起 GET请求 (带参数)
可以在请求的 URL 地址后面通过 ? 的形式携带查询参数
let xhr = new XMLHttpRequest()
xhr.open('get','http://www.liulongbin.top:3009/api/get?name=毛毛&age=18')
xhr.send()
xhr.addEventListener('load',function(){
console.log(xhr.response);
})
XMLHttpRequest 发起 POST请求(携带请求体数据)
当需要携带请求体数据时,需要进行额外的两步操作:
在 xhr.open() 之后,调用 xhr.setRequestHeader() 函数,指定请求体的编码格式
在 xhr.send() 中,指定要提交的请求体数据
let xhr = new XMLHttpRequest()
xhr.open('post','http://www.liulongbin.top:3009/api/post')
// 指定编码格式
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')
// 指定要提交的请求体数据
xhr.send('name=rose&age=21')
xhr.addEventListener('load',function(){
console.log(xhr.response);
})