利用Promise封装jquery ajax
利用Promise封装jquery ajax
源码
;(function ($) {
let request = function(url,method,params,body=false){
return new Promise((resolve, reject) =>{
let aj = {
url: url,
method:method,
dataType:'json',
success(returnData) {
resolve(returnData);
},
error(error){
reject(error);
}
};
if(params){
if (body == true){
aj.contentType = 'application/json';
}
aj.data = JSON.stringify(params);
}
$.ajax(aj);
});
}
window.$ajax = {
get(url,params){
return request(url,'GET',params);
},
post(url,data){
return request(url,'POST',data,true);
},
put(url,data){
return request(url,'PUT',data,true);
},
delete(url,data){
return request(url,'DELETE',data,true);
}
}
})(jQuery);
使用
let api = '请求地址';
//查询
let params = {
name:"张三",
age:21
};
$ajax.get(api,params).then(returnData => {
console.log(returnData);
}).catch(error => {
console.log(error);
})
//根据id获取
let id = "记录id";
$ajax.get(api+'/'+id).then(returnData => {
console.log(returnData);
}).catch(error => {
console.log(error);
});
//修改实体
let form= {
id:id,
name:"李四",
age:21
};
$ajax.put(api,form).then(returnData => {
console.log(returnData);
}).catch(error => {
console.log(error);
})
//添加实体
let form= {
name:"王五",
age:18
};
$ajax.post(api,form).then(returnData => {
console.log(returnData);
}).catch(error => {
console.log(error);
})
//删除
let list = [1,2,3]; //id列表
$ajax.delete(api,list).then(returnData => {
console.log(returnData);
}).catch(error => {
console.log(error);
});
不积跬步无以至千里