1.1 XMLHttpRequest的概念
XMLHttpRequest是浏览器内置的一个构造函数。所以使用的时候需要 new 作用:基于 new 出来的 XMLHttpRequest 实例对象,可以发起 Ajax 的请求。 axios 中的 axios.get()、axios.post()、axios() 方法,都是基于 XMLHttpRequest(简称:XHR) 封装
1.2 XMLHttpRequest的使用
主要的 4 个实现步骤:
-
创建 xhr 对象
-
调用 xhr.open() 函数
-
调用 xhr.send() 函数
-
监听 load 事件
// 创建 xhr 对象
const xhr = new XMLHttpRequest();
// 调用 xhr.open() 函数
xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks');
// 调用 xhr.send() 函数
xhr.send();
// 监听 load 事件
xhr.addEventListener('load', function() {
console.log(xhr.response);
});
1.3 GET请求携带参数
GET请求参数直接放到路径的最末尾就可以
// 创建 xhr 对象
const xhr = new XMLHttpRequest();
// 调用 xhr.open() 函数 -- get参数
xhr.open('GET', 'http://www.li