源代码
var ajax=(options)=>{
// 1. 首先简单验证传进来的参数是否合法
if(!options) return undefined;
// 2. 对参数容错处理
options.method = options.method ? options.method.toUpperCase() : 'GET'; // 默认 GET 请求
options.data = options.data || {};
options.type = options.type || 'FormData';
if(options.type==='JSON'){
options.data = JSON.stringify(options.data)
}else if(options.type==='FormData'){
var formData = [];
for(let key in options.data) { // Object.keys.forEach
formData.push(''.concat(key, '=', options.data[key]))
}
options.data = formData.join('&') //eg: a=b&c=d&e=f
}
// 3. 实例化 XMLHttpRequest 对象,并进行一些设置
var xmlhttp = new XMLHttpRequest();//获取对象
// 4. 处理请求回调
xmlhttp.onreadystatechange = function(){//设置回调函数
if(xmlhttp.readyState == 4){//这里的4是请求的状态码,代表请求已经完成
if(xmlhttp.status == 200 || xmlhttp.status == 304){//这里是获得响应的状态码,200代表成功,304代表无修改可以直接从缓存中读取
options.success(xmlhttp)
}else if(xmlhttp.status==500||xmlhttp.status==404){
options.failure(xmlhttp)
}else {
options.failure(xmlhttp)
}
}
}
// 5. 打开请求
xmlhttp.open(options.method,options.url,true);
// 6. 设置请求头
if(options.header){
for(let key in options.header){
xmlhttp.setRequestHeader(key, options.header[key])
}
}
// 7. 发送请求
xmlhttp.send(options.method==='POST'?options.data:null);//GET请求
}
DEMO
ajax({
url: '',
method: 'POST',
type: 'JSON',
data: {},
success: function(res) {
console.log(res)
},
failure: function(err) {
console.log(err)
}
})
参考文章
https://www.runoob.com/ajax/ajax-examples.html
https://blog.csdn.net/tinsine/article/details/90231546