使用原生JS封装一个ajax

时间:2023-03-09 00:24:49
使用原生JS封装一个ajax
function ajax(data){
//第一步,创建XHR对象
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();//标准的浏览器
}else{
xhr = new ActiveXObject('Microsoft.XMLHTTP');//万恶的IE浏览器
}
//第二步,准备发送前的一些配置文件
var type = data.type == 'get' ? 'get' : 'post';
var url = '';
if(data.url){
url = data.url;
if(type == 'get'){
url += "?" + data.data + "&_t + new Date().getTime();
}
} var flag = data.asyn == 'true' ? 'true' : 'false';
xhr.open(type,url,type);
//第三步,执行发送的动作
if(type == 'get'){
xhr.send(null);
}else{
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(data.data);
}
//指定回掉函数
xhr.onreadystatechange = function(){
if(this.readyState == 4){
if(this.status == 200){
if(typeof data.success == 'function'){
var d = data.dataType == 'xml'?xhr.responseXML:xhr.responseText;
data.success(d);
}
}else{
if(typeof data.failure == 'function'){
data.failure();
}
}
}
}
}

其中传入的data属性为:

data={
data:"",
dataType:"xml/json",
type:"get/post",
url:"",
asyn:"true/false",
success:function(){},
failure:function(){}
}