一. 什么是ajax
AJAX全称(Async Javascript and XML), 即异步的JavaScript 和XML,是一种创建交互式网页应用的网页开发技术,可以在不重新加载整个网页的情况下,与服务器交换数据,并且更新部分网页
二.实现过程
1.创建 Ajax的核心对象 XMLHttpRequest
对象
const xhr = new XMLHttpRequest();
2.通过这个对象的 open()
方法创建HTTP请求,与服务端建立连接
xhr.open(method, url, [async][, user][, password])
- method: 请求方式,常见的有GET、POST
- url: 请求地址
- async: 是否异步,默认为true
- user: [可选]用户名用于认证用途;默认为null
- password: [可选]密码用于认证用途,默认为null
3.通过这个对象的send()
方法向服务端发起请求
xhr.send([body])
-
body: 在 XHR 请求中要发送的数据体,如果不传递数据则为 null
-
如果使用GET请求发送数据的时候,需要注意如下:
- 将请求数据添加到open()方法中的url地址中
- 发送请求数据中的send()方法中参数设置为null
// get请求将请求参数放入url里面
xhr.open('GET',url + '?' + params, true)
xhr.send(null)
4.通过这个对象的onreadystatechange
方法监听服务端的通信状态
主要监听的属性为readyState
状态, 它变化时会触发readystatechange
事件,可以通过设置监听函数,来处理请求成功后的结果
readyState
一共有 5 个状态,如下图显示
5.接受并处理服务端向客户端响应的数据结果
当对象的 readyState
变为 4 的时候,代表服务器返回的数据接收完成,这个时候可以通过判断请求的状态,如果状态是 2xx 或者 304 的话则代表返回正常。
const xhr = new XMLHttpRequest()
xhr.onreadystatechange = function(e){
if (request.readyState !== 4) return;
// 当请求成功时
const status = xhr.status
if (status === 200) {
console.log(xhr.responseText) // 服务端返回的结果
} else {
console.error(status);
}
}
xhr.open('POST','http://xxxx')
xhr.send(data)
6.将处理结果更新到 HTML页面中
三.封装一个ajax
//封装一个ajax请求
function ajax(options) {
let promise = new Promise(function (resolve, reject) {
// 创建核心对象
const xhr = new XMLHttpRequest();
// 处理传入参数
options = options || {};
options.type = (options.type || "GET").toUpperCase();
options.url =
options.type === "GET" ? options.url + "?" + options.data : options.url;
options.data = options.type === "GET" ? null : options.data;
// 设置响应的数据类型
xhr.responseType = options.dataType || "json";
// 设置请求头信息
xhr.setRequestHeader("Accept", "application/json");
// 创建HTTP请求
xhr.open(options.type, options.url, true);
// 发送数据
xhr.send(options.data);
// 监听数据变化
xhr.onreadystatechange = function (e) {
if (this.readyState !== 4) return;
if (this.status == 200) {
resolve(this.response);
} else {
reject(new Error(this.statusText));
}
};
// 设置错误监听函数
xhr.onerror = function() {
reject(new Error(this.statusText));
};
});
return promise;
}
ajax({
type: "post",
dataType: "json",
data: {},
url: "https://xxxx"
});
参考文献