实现过程
1创建XMLHttpRequest对象
2指定响应函数
- responseText 获得字符串形式的响应数据。
- responseXML 获得 XML 形式的响应数据。
3打开连接(指定请求)
4发送请求
5创建响应函数
- onreadystatechange 存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。
- readyState 存有 XMLHttpRequest 的状态。
从 0 到 4 发生变化。
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪 - status 200: "OK 404: 未找到页面
基本的写法
let req = new XMLHttpRequest();
req.open("get", "mockData/usersinfo.json", true);
req.send();
req.onreadystatechange = function () {
if (req.readyState == 4 && req.status == 200) {
var result= req.responseText;
}
}
简单的封装
const ajax = (url, method, async, data) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.onreadystatechange = () => {
// 已经接收到全部响应数据,而且已经可以在客户端使用了
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.responseText))
} else if (xhr.status > 400) {
reject('发生错误')
}
}
}
xhr.open(method, url, async)
xhr.send(data || null)
})
}