function $ajax(obj){
//封装一个对象转成a=1&b=2&c=3的字符串样式
function objstring(obj){
//判断传进来的obj是不是一个对象
if(Object.prototype.toString.call(obj).slice(8,-1)=‘Object’){
let arr=[ ];
for(let attr in obj){
arr.push(attr+’=’+obj[attr]);
}
return arr.join(’&’)//得到a=1&b=2&c=3样式
}else{
throw new Error(‘你输入的不是一个纯粹的对象’)
}
}
//ajax经典4步取
let xhr=XMLHttpRequest( );
//默认get请求 此参数可以忽略
obj.type=obj.type || ‘get’ ;
//接口地址不能为空
if(!obj.url){
throw new Error(‘接口地址不能为空!’ );
}
//判断传输的数据obj.data存在并且是一个对象
if(obj.data){
if(Object.prototype.toString.call(obj.data).slice(8,-1)=‘Object’){
obj.data=objstring(obj.data);
}else{
obj.data=obj.data;
}
}
//传输数据存在并且是get请求
if(obj.data && obj.type=‘get’){
obj.url+= ‘?’+obj.data;
}
//是否异步obj.async 默认异步 此参数可以省略
if(obj.async=‘flase’ || obj.async=false){
obj.async=‘false’ ;
}else{
obj.async=‘true’ ;
}
xhr.open(obj.type,obj.url,obj.async);
//传输数据存在并且是get请求
if(obj.data && obj.type=‘post’){
xhr.setRequestHeader(‘content-type’, ‘application/x-www- form-urlencoded’);
xhr.send(obj.data);
}else{
xhr.send();
}
//存在异步
if(obj.async){
xhr.onreadystatechange=function(){
if(xhr.readyState=‘4’){
if(xhr.status=‘200’){
//方法存在且是个函数
obj.success && typeof(obj.success)=‘function’ && obj.success(xhr.responseText);
}else{
obj.error && typeof(obj.error)=‘function’ && obj.error(‘接口地址有误!’ + xhr.status);
}
}
}else{
if(xhr.status=‘200’){
obj.success && typeof(obj.success)=‘function’ && obj.success(xhr.responseText);
}else{
obj.error && typeof(obj.error)=‘function’ && obj.error(‘接口地址有误!’ + xhr.status);
}
}
}
$ajax({
type: ‘get’, //可不写 默认为get
url: ‘http://www.kuitao8.com/api/joke’, //接口必填
data:{ //传入的数据
a:1,
b:2,
c:3
},
async:true, //可不写 默认为true
success:function(result_one){ //把函数里的结果当作参数传到外面使用
console.log(JSON.parse(result_one));
},
error:function(result_two){
console.log(result_two);
}
})