1. axios 简介与安装
1、axios简介
1. vue本身不支持发送AJAX请求,需要使用vue-resource、axios等插件实现
2. axios是一个基于Promise的HTTP请求客户端,用来发送请求,也是vue2.0官方推荐的,同时不再对vue-resource进行更新和维护
3. 参考:GitHub上搜索axios,查看API文档:https://github.com/axios/axios
2、安装axios
1. npm install axios -S # 也可直接下载axios.min.js文件
2. 下载后即到 C:Users om
ode_modulesaxiosdist 路径下找到 axios.min.js 文件
1.2 axios 基本用法
axios参考博客:https://www.jianshu.com/p/68d81da4e1ad
https://www.cnblogs.com/yiyi17/p/9409249.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>发送AJAX请求</title>
</head>
<body>
<div id="itany">
<button @click="sendGet">GET方式发送AJAX请求</button>
</div>
<script src="js/vue.js"></script>
<script src="js/axios.min.js"></script>
<script src="js/qs.js"></script>
<script>
window.onload=function(){
new Vue({
el:'#itany',
data:{
uid:''
},
methods:{
sendGet(){
// 1、发送get请求
axios({
url: 'http://127.0.0.1:8000/data/', //1、请求地址
method: 'get', //2、请求方法
params: {ids: [1,2,3],type: 'admin'}, //3、get请求参数
paramsSerializer: params => { //4、可选函数、序列化`params`
return Qs.stringify(params, { indices: false })
},
responseType: 'json', //5、返回默认格式json
headers: {'authorization': 'xxxtokenidxxxxx'}, //6、认证token
})
// 2、回调函数
.then(resp => {
console.log(resp.data);
})
// 3、捕获异常
.catch(err => {
console.log('请求失败:'+err.status+','+err.statusText);
});
}
}
});
}
</script>
</body>
</html>
post: axios发送post请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>发送AJAX请求</title>
</head>
<body>
<div id="itany">
<button @click="sendPost">POST方式发送AJAX请求</button>
</div>
<script src="js/vue.js"></script>
<script src="js/axios.min.js"></script>
<script src="js/qs.js"></script>
<script>
window.onload=function(){
new Vue({
el:'#itany',
data:{
uid:''
},
methods:{
sendPost(){
// 1、发送post请求
axios({
url: 'http://127.0.0.1:8000/data/', //1、请求地址
method: 'post', // 2、请求方法
data: Qs.stringify( //3、可选函数、序列化`data`
{ids: [1,2,3],type: 'admin'}, //4、提交数据
{ indices: false } // indices: false
),
responseType: 'json', //5、返回默认格式json
headers: {'authorization': 'xxxtokenidxxxxx'},//6、身份验证token
})
// 2、回调函数
.then(resp => {
console.log(resp.data);
})
// 3、捕获异常
.catch(err => {
console.log('请求失败:'+err.status+','+err.statusText);
});
}
}
});
}
</script>
</body>
</html>
views.py后端测试接口
def data(request):
if request.method == 'GET':
token_id = request.META.get('HTTP_AUTHORIZATION') # header中的tokenid
print(request.GET.getlist('ids')) # 获取get请求中列表
data = {
'id':1,
'name': 'zhangsan'
}
return HttpResponse(json.dumps(data))
elif request.method == 'POST':
token_id = request.META.get('HTTP_AUTHORIZATION') # header中的tokenid
print(request.POST.getlist('ids')) # 获取post请求中的列表
data = {
'id':1,
'name': 'zhangsan',
'method': 'POST'
}
return HttpResponse(json.dumps(data))
复制代码
复制代码
#1、qs用途: 在 axios中,利用QS包装data数据
#2、安 装: npm install qs -S
#3、常见用法:
'''
import Qs from 'qs';
Qs.stringify(data);
Qs.parse(data)
'''
3、vuejs借助axios发送ajax请求(同级目录下创建以下两个文件)
*user.json*
{
"id":1001,
"name":"秋香",
"age":18
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>发送AJAX请求</title>
</head>
<body>
<div id="itany">
<button @click="send">发送AJAX请求</button>
</div>
<script src="js/vue.js"></script>
<script src="js/axios.min.js"></script>
<script>
window.onload=function(){
new Vue({
el:'#itany',
data:{
user:{
// name:'alice',
// age:19
},
uid:''
},
methods:{
send(){
axios({
method:'get',
url:'user.json'
}).then(function(resp){ // 请求成功调用此函数
console.log(resp.data); // {id: 1001, name: "秋香", age: 18}
}).catch(resp => { // 请求失败调用此函数
console.log('请求失败:'+resp.status+','+resp.statusText);
})
}
}
});
}
</script>
</body>
</html>
复制代码
<?php
//获取参数
$name=$_POST['name'];
$age=$_POST['age'];
//响应数据
echo '姓名:',$name,',年龄:',$age;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>发送AJAX请求</title>
</head>
<body>
<div id="itany">
<button @click="sendGet">GET方式发送AJAX请求</button>
</div>
<script src="js/vue.js"></script>
<script src="js/axios.min.js"></script>
<script>
window.onload=function(){
new Vue({
el:'#itany',
data:{
user:{
// name:'alice',
// age:19
},
uid:''
},
methods:{
sendGet(){ // axios.get('server.php?name=tom&age=23')
axios.get('server.php',{
params:{
name:'alice',
age:19
}
})
.then(resp => {
console.log(resp.data);
}).catch(err => {
console.log('请求失败:'+err.status+','+err.statusText);
});
},
}
});
}
</script>
</body>
5、vuejs借助axios发送post请求
- axios默认发送数据时,数据格式是Request Payload,并非我们常用的Form Data格式,
2. 所以参数必须要以键值对形式传递,不能以json形式传参
3. 传参方式:
1. 自己拼接为键值对
2. 用transformRequest,在请求发送前将请求数据进行转换
3. 如果使用模块化开发,可以使用qs模块进行转换
<?php
//获取参数
$name=$_POST['name'];
$age=$_POST['age'];
//响应数据
echo '姓名:',$name,',年龄:',$age;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>发送AJAX请求</title>
</head>
<body>
<div id="itany">
<button @click="sendPost">POST方式发送AJAX请求</button>
</div>
<script src="js/vue.js"></script>
<script src="js/axios.min.js"></script>
<script>
window.onload=function(){
new Vue({
el:'#itany',
data:{
user:{
name:'alice',
age:19
},
uid:''
},
methods:{
sendPost(){
// axios.post('server.php',{ // 这个是官方给出的post请求,但是后天无法收到
// name:'alice',
// age:19
// })
// axios.post('server.php','name=alice&age=20&') //方式1
axios.post('server.php',this.user,{
transformRequest:[ // 在发送请求前可以改变要传的数据
function(data){
let params='';
for(let index in data){
params+=index+'='+data[index]+'&'; // 拼接成:name=alice&age=20& 的字符串
}
return params;
}
]
})
.then(resp => {
console.log(resp.data);
})
.catch(err => {
console.log('请求失败:'+err.status+','+err.statusText);
});
},
}
});
}
</script>
</body>
</html>