提示:文章为 学习过程中的记录实践笔记。有问题欢迎指正。
前言
AJAX 不是编程语言,是一种从网页访问web服务器的技术。
可以实现不刷新页面更新网页
在页面加载后从服务器请求/获取数据
在后台向服务器发送数据
AJAX 等价于 Asynchronous JavaScript And XML.
一、实现步骤
- 创建 XMR
XMLHttpRequest()
const xhr = new XMLHttpRequest();
- 配置请求
open(method,url,async,user,psw)
参数说明: 请求方式,请求地址,是否异步,可选的用户名,可选的密码
请求方式 method | 是否异步 |
---|---|
GET,POST,PUT,DELETE 等 | true(异步) false(同步) |
xhr.open('GET', 'http://localhost:5500/javascript/ajax/data.json')
- 发送请求
send()
xhr.send();
- 接收请求 - 定义接收到(加载)请求时调用的函数
onload
当请求完成时会被调用
xhr.onload = function(){
//处理返回值
}
onreadystatechange
当readyState属性发生变化时调用
二、完整示例
使用 onload 接收数据
使用 onreadystatechange
readyState
不同状态
0:请求未初始化
1:服务器连接已建立
2:请求已收到
3:正在处理请求
4:请求已完成且响应已就绪
xhr.onreadystatechange = function () {
// console.log(xhr.readyState, xhr.status)
// 接收状态码 4:解析完成 http状态码 200~299 都是正确的 常见 200
if (xhr.readyState === 4 && xhr.status === 200) {
console.log('数据解析完成', xhr.responseText)
} else if (xhr.readyState === 4 && xhr.status === 404) {
console.log('请求地址不存在')
}
}
三、封装
//ajax.js
function ajax(option) {
const options = {
method: 'GET',
url: '',
data: '',
success: function () { },//成功回调函数
error: function () { },
...option,
}
const xhr = new XMLHttpRequest();
const method = options.method.toUpperCase();
const url = options.url;
let data = null;
if (option.data) {
data = Object.keys(options.data).map(key => key = options.data[key]).join('&');
}
if (method === 'GET' && data) {
url += '?' + data;
}
xhr.open(method, url);
if (method === 'POST') {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
const response = xhr.getResponseHeader('Content-Type').includes('json') ? JSON.parse(xhr.responseText) : xhr.responseText;
options.success && options.success(response);
} else {
options.error && options.error(xhr.status);
}
}
};
xhr.send(method === 'POST' ? data : null);
}
export default ajax;
调用封装
总结
通俗的说,就像是拨打电话,
- 首先要拿起电话
new XMLHttpRequest()
- 打开通讯录拨号/查看通讯录
open(method,url)
\ - 点击拨打
send()
- 等待接通
onreadystatechange
|| 接通后onload