第一步:创建ajax对象:new XMLHttpRequest()
第二步:建立请求连接,并配置ajax请求地址与请求方式:ajax对象.open("方法",url)
第三步:发送ajax请求:ajax对象.send()
第四步:监听ajax请求进度,获取服务器的响应内容:ajax对象.onreadystatechange
当xhr.readystate为4和status为200的时候,就可以得到后端响应过来的数据
第五步:处理服务器响应数据JSON.parse,JSON.stringify,并渲染页面
function ajax(options) {
const { type, dataType, data, timeout, url, success, error } = options;
var params = formatParams(data);
var xhr;
//考虑兼容性
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveObject) {
//兼容IE6以下版本
xhr = new ActiveXobject("Microsoft.XMLHTTP");
}
//启动并发送一个请求
if (type == "GET") {
xhr.open("GET", url + "?" + params, true);
xhr.send();
} else if (type == "POST") {
xhr.open("post", url, true);
//设置表单提交时的内容类型
//Content‐type数据请求的格式
xhr.setRequestHeader(
"Content‐type",
"application/x‐www‐form‐urlencoded"
);
xhr.send(params);
}
// 设置有效时间
setTimeout(function () {
if (xhr.readySate != 4) {
xhr.abort();
}
}, timeout);
// 接收
// options.success成功之后的回调函数 options.error失败后的回调函数
//xhr.responseText,xhr.responseXML 获得字符串形式的响应数据或者XML形式的响应数据
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var status = xhr.status;
if ((status >= 200 && status < 300) || status == 304) {
success && success(xhr.responseText, xhr.responseXML);
} else {
error && error(status);
}
}
};
}
//格式化请求参数
function formatParams(data) {
var arr = [];
for (var name in data) {
arr.push(
encodeURIComponent(name) + "=" + encodeURIComponent(data[name])
);
}
arr.push(("v=" + Math.random()).replace(".", ""));
return arr.join("&");
}