function axios({method,url,params,data}){
//方法转换大写
method=method.toUpperCase();
return new Promise((resolve,reject)=>{
//1.创建对象
const xhr=new XMLHttpRequest();
//2.初始化 url中要放参数 所以要将params对象转化为字符串 a=100&b=200
let str='';
for(let k in params){
str+=`${k}=${params[k]}&`;
}
str=str.slice(0,-1)
xhr.open(method,url+'?'+str);
//3.发送
if(method==='POST'||method==='PUT'||method==='DELETE'){
//设置请求头信息
xhr.setRequestHeader('Content-type','application/json');
//设置请求体 data为对象 要转化为字符串类型
xhr.send(JSON.stringify(data))
}else{
xhr.send();
}
//对响应结果做预设 设置类型
xhr.responseType='json';
//4.处理结果
xhr.onreadystatechange=function(){
if(xhr.readyState===4){
if(xhr.status>=200&&xhr.status<300){
//成功的状态
resolve({
status:xhr.status,
message:xhr.statusText,
body:xhr.response
})
}else{
//失败的状态
reject(new Error('请求失败,失败的状态码为'+xhr.status))
}
}
}
})
}
//添加get方法
axios.get=function(url,options){
//发送AJAX请求 get中两个参数url有了 要对options做一个合并 get不传参
let res=Object.assign(options,{method:'GET',url:url})
axios(res)
}
//添加post方法
axios.get=function(url,options){
let res=Object.assign(options,{method:'POST',url:url})
axios(res)
}
//添加put方法
axios.get=function(url,options){
let res=Object.assign(options,{method:'PUT',url:url})
axios(res)
}
axios方法封装
最新推荐文章于 2024-10-17 16:16:18 发布