一、GET请求
static Get(url,param,success,failure){
/**
var param = {
name:'abc',
age:20
}
**/
// 拼接参数
if(param){
var keys = Object.keys(param);
var totalParam = '';
keys.forEach((key,i)=>{
var mark = '?';
if (i > 0) {
mark = '&'
}
var value = param[key];
totalParam += mark;
totalParam = totalParam + key + '=' + value;
})
url = url + totalParam;
}
// 发送请求
fetch(url)
.then((response)=>response.json())
.then((json)=>{
// 请求成功,并且解析数据为json的时候调用
if(success){
success(json);
}
})
.catch((error)=>{
if(failure){
failure(error);
}
})
}
二、Post请求:
// Post的数据格式
static ParamType = {
ParamTypeJSON:'application/json',
ParamTypeURL:'application/x-www-form-urlencoded'
}
// 数据格式为URL:'application/x-www-form-urlencoded'
static PostWithUrlParam(url,param,success,failure){
this.Post(url,param,this.ParamType.ParamTypeURL,success,failure);
}
// 数据格式为JSON:'application/json'
static PostWithJsonParam(url,param,success,failure){
this.Post(url,param,this.ParamType.ParamTypeJSON,success,failure);
}
// 处理请求参数
static resolveParam(param,paramType){
// 没有参数,返回空
if (!param) return '';
if(paramType == 'application/json'){
return JSON.stringify(param);
} else if (paramType == 'application/x-www-form-urlencoded'){
// 获取key
var totalParam = '';
var i = 0;
for (key in param){
var mark = '';
if (i > 0){
mark = '&'
}
var value = param[key];
// name=abc&age=20
totalParam += mark + key + '=' + value;
i++;
}
return totalParam;
}
}
static Post(url,param,paramType,success,failure){
// 处理请求参数
this.resolveParam(param,paramType);
var body = JSON.stringify(param);
// 定制请求
var optionals = {
method:'POST',
headers:{
'Content-Type':paramType
},
body:body
}
// 发送请求
fetch(url,optionals)
.then((response)=>response.json())
.then((json)=>{
if(success){
success(json);
}
})
.catch((error)=>{
if(failure){
failure(error);
}
})
}