function ajax(obj){
if(typeof obj!="object"){
console.error("参数类型错误");
return;
}
var url=obj.url;
if(obj.url==undefined){
console.error("地址必须指定");
return;
}
var type=obj.type||"get";
var asynch=obj.asynch===undefined?true:obj.asynch; //判断是否为异步连接
var dataType=obj.dataType||"text";
//判断传入的数据类型
var data=obj.data;
if(typeof data=="object"){
var temp="";
for(var i in data){
temp+=i+"="+data[i]+"&";
}
data=temp.slice(0,-1);
}
//监听函数
var xmlObj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
xmlObj.onreadystatechange=function(){
if(xmlObj.readyState==4){
if(xmlObj.status==200){
var result;
if(dataType=="XML"){
result=xmlObj.responseXML;
}else if(dataType=="json"){
result=eval("("+xmlObj.responseText+")");
}else if(dataType=="text"){
result=xmlObj.responseText;
}
obj.success(result);
}
}
}
//判断获取方式
if(type=="get"){
xmlObj.open("get",url+"?"+data,asynch);
xmlObj.send()
}else if(type=="post"){
xmlObj.open("post",url,asynch);
xmlObj.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlObj.send(data);
}
}
基于promise的ajax
function ajax({ url = '', type = 'get', dataType = 'json', asynch = 'true' }) {
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open(type, url, asynch);
xhr.responseType = dataType;
xhr.onload = function () { //xhr.readState=4 xhr.sratus=200
if (xhr.status === 200) {
resolve(xhr.response);
} else {
reject('error');
}
}
xhr.onerror = function (err) {
reject(err);
}
xhr.send();
})
}
网友评论