axios中文文档|axios中文网
http://www.axios-js.com/zh-cn/docs/
一、axios 原生 JavaScript 请求
- get 方式请求随机笑话
- post 方式请求注册接口
请求结果打印在控制台
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</style>
</head>
<body>
<input type="button" value="get" class="get">
<input type="button" value="post" class="post">
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
// 随机笑话
// https://autumnfish.cn/api/joke/list?num=3
document.querySelector(".get").onclick = function(){
axios.get("https://autumnfish.cn/api/joke/list?num=3")
.then(function(response){
console.log(response);
},function(err){
console.log(err);
})
}
document.querySelector(".post").onclick=function(){
axios.post("https://autumnfish.cn/api/user/reg",{username:"dy"})
.then(function(response){
console.log(response);
},function(err){
console.log(err);
})
}
</script>
</body>
</html>
二、axios 在 vue 中的使用
- get 方式请求随机笑话,请求结果显示在页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
<title>Document</title>
</style>
</head>
<body>
<div id="app">
<input type="button" value="get" @click="getJoke">
<p>{{joke}}</p>
</div>
<script>
// 随机笑话
// https://autumnfish.cn/api/joke/list?num=3
var app = new Vue({
el:"#app",
data:{
joke:"joke"
},
methods:{
getJoke:function(){
var that = this;
axios.get("https://autumnfish.cn/api/joke/list?num=1")
.then(function(response){
console.log(response.data);
console.log(response.data.jokes);
that.joke = response.data.jokes[0];
},function(err){
console.log(err);
})
}
}
})
</script>
</body>
</html>
- get 方式请求天气接口,请求结果打印在控制台
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
<title>Document</title>
</style>
</head>
<body>
<div id="app">
<input type="text" v-model="city" @keyup.enter="searchWeather">
<a href="#" @click="changeCity('北京')">北京</a>
<a href="#" @click="changeCity('西安')">西安</a>
<a href="#" @click="changeCity('南京')">南京</a>
<a href="#" @click="changeCity('长春')">长春</a>
<p>in:{{city}}</p>
</div>
<script>
var app = new Vue({
el:"#app",
data:{
city:'',
weatherList:[]
},
methods:{
searchWeather:function(){
axios.get("http://wthrcdn.etouch.cn/weather_mini?city="+this.city)
.then(function(response){
console.log(response);
},function(err){
console.log(err);
})
},
changeCity:function(city){
this.city=city;
this.searchWeather();
}
}
})
</script>
</body>
</html>