ajax:
1、创建XMLHttpRequest对象
2、open方法(type,url,async)
3、send方法(params)
4、readyStateChange
get 和 post 区别:
1、get参数拼接到url后边,post参数是放到send方法里的
2、get参数不能识别中文和特殊符号,需要通过encodeURI进行转码,而post支持中文
3、get有缓存,请求需要带上时间戳或者随机数,而post没有缓存
4、get不需要设置请求头,post需要设置请求头
ajax({
url: '',
data: {
a: 1,
b: 2
},
type: 'get',
success: function(){},
error: function(){},
timeout: 1000,
complate: function(){}
})
function ajax(options){
const {url, data, type, success, error, timeout, complate} = options;
var xml = new XMLHttpRequest();
let method = type.toUpperCase();
if(method === 'GET'){
xml.open(method, url + formatData(data), true);
xml.send();
}else if(method === 'POST'){
xml.open(method, url, true);
xml.send(data);
xml.setRequestHeader();
}
setTimeout(()=>{
xml.abort();
}, timeout)
xml.onreadystatechange = function(){
if(xml.state === 200 && xml.status === 4){
success && success(xml.responseText)
}else {
error && error();
}
complate && complate();
}
}
function formatData(obj){
// '?a=1&b=2&time='+new Date().getTime() {a:1,b:2}
let res = '?';
for(let key in obj){
res += key + '=' + encodeURI(obj[key]) + '&'
}
res += 'time=' + new Date().getTime();
return res;
}