1.下载并导入axios.js文件和axios.min.js到文件中
2.在script标签中构造一个函数按照下面的模板调用API接口。
axios.get(`API接口`)
.then(
(res)=>{
alert("success");//弹出success窗口
consolo.log(res);//输出数据到控制台
}
)//访问成功,通过res得到从api获取的数据
.catch(
()=>{
alert("error");
}
)//访问异常,输出error
.finally(
()=>{
}
);//访问结束后一定会调用的方法
具体代码解释:
首先axios.get(`API接口`)参数是接口的地址,并且要用反引号括起来。
然后分两种情况:
1.访问成功会调用then(),通过res可以得到API传过来的数据。
2.访问失败会调用catch()
最后无论失败与否都会调用finally()
对then中的代码进行修改,获取数值后,调用其他函数从而实现其他的功能。
例子:查询城市时间
在then中获取到reg.data.result,并赋值给Time,然后调用outputTime函数将时间显示在网页上。
function GetTime(city){
axios.get(`接口链接`)
.then(
(res)=>{
console.log(res);
if(res.msg=="null")alert("请查询同一时区的其他城市");
else if(res.msg="success"){
Time=res.data.result;
// console.log(Time);
outputTime();
}
}
)
.catch(
()=>{
alert("error");
}
)
.finally(
()=>{
}
);
}