最近项目中用到了axios进行请求数据,从百度看了一圈,基本将两种方法都分开写了,因为项目从零开始,所以post和get方法都会用到,想把它封装为一个函数,便于管理使用,没看到合适的资料,自己尝试写了一下,作为笔记方便以后使用:
function ajax_curl(posttype, url, params, cb) {
var method_type = posttype.toLowerCase();
if(method_type == "get") {
//get和post传参不同,get最前变需要增加"params:"而post不需要
if(!params.params){
params={params:params}
}
return axios.get(url, params).then(function(res) {
if(res.data.code == 1) {
//正确返回时的处理
cb(res.data.data);
} else if(res.data.code == -1) {
//登录获取的sessionkey失效等逻辑的处理
} else {
//code=0的处理
alert(res.data.msg);
}
})
} else if(method_type == "post") {
//get和post传参不同,get最前变需要增加"params:"而post不需要
return axios.post(url, params).then(function(res) {
if(res.data.code == 1) {
//正确返回时的处理
cb(res.data.data);
} else if(res.data.code == -1) {
//登录获取的sessionkey失效等逻辑的处理
} else {
//code=0的处理
alert(res.data.msg);
}
})
}
}
几点说明:①posttype(请求方式)==post或者get;
②url(路径);
③params(参数:是对象形式);
④cb回调函数function
实例(举例)
tool.ajax_curl("get","http:×××",{'page':1,'keyword':"哈哈"},function(res){
console.log(res)
});
tool.ajax_curl("post","http:×××",{'username':'liming','password':"123"},function(res){
console.log(res)
});