function ajax(opt){
let default_opt={
url:'',
method:'post',
async:'true',
data:{},
callback:null,
};
}
// 合并参数
let new_opt=Object.assign(default_opt,opt);
// 创建ajax
// 实例化 ajax
let xhr=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHTTP');
xhr.onreadystatechange=function(){
// 0: 请求未初始化
// 1: 服务器连接已建立
// 2: 请求已接收
// 3: 请求处理中
// 4: 请求已完成,且响应已就绪
if(xhr.readyState===4&&xhr.status===200){
new_opt.callback&& new_opt.callback(xhr.reponseText)
}
let search='';
if(new_opt.method.toUpperCase()==='GET'){
search='?'+Object.keys(new_opt.data).map(function(key){
return key+'='+new_opt.data[key]}).join('&');
}
xhr.open(new_opt.method,new_opt.url+search,new_opt.async);
let data=null;
if(new_opt.method.toUpperCase()==='POST'){
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
data=JSON.stringify(new_opt.data)
}
xhr.send(data);
}
网友评论