下面是vue2用法。
前言
安装axios 用来在vue中更好的和服务器端进行数据通信 。
网络工具库:在前端用的最多的就是axios。vuex 前端全局共享。
axios实现了不用原生js大量封装ajax.
axios特性:
从浏览器中创建XMLHttpRequest
从node.js发出http请求
支持Promise APl
拦截清求和响应
转换清求和响应数据
取消请求
自动转换JSON数据
客广端支持防止CSRF/XSRF
axios支持多种请求方式:
axios(config)
axios.request(config)
axios.get(url[,config])
axios.post(url[data[,config])
axios.put(url[data[,config])
一、安装axios
1.安装命令
npm install -save axios
或
npm install axios

2.在main.js中导入:
vucli3:
// 全局引入axios,并进行全局注册
import axios from 'axios'
Vue.prototype.$axios = axios
然后就可以在组件中使用啦。
二、get请求
我代码写的很清楚了,都是运行好的,可以单独复制,就不再另写了,直接放代码。
版本:vue2
vue路径:d://allvue/vue3demo2/src/conmenents/axios/gettest.vue
python路径:d://ajax/worktwo/vue3demo2/ views 和worktwo/urls.
gettest.vue
<template>
<div>
<h3>下面是axios的使用方法:Get方式 </h3>
<h5> python:打开,d/ajax/worktwo/worktwo里。 vuedemo3 </h5>
<h3>get不传参,只接收</h3>
<div class="a">
<button @click="func()" type="button" class="btn btn-primary">get不传参测试按钮</button>
<p>{{msg0}}</p>
</div>
<div class="a">
<h4>方式一:路径?传参</h4>
<button @click="datafun1()" type="button" class="btn btn-primary">get(路径?id=1)测试按钮</button>
<p>{{msg1}}</p>
</div>
<div class="a">
<h4>方式二:params传参</h4>
<button @click="datafun2()" type="button" class="btn btn-primary">get params传参测试</button>
<p>{{msg2}}</p>
</div>
<div class="a">
<h4>方式三:params传参,写的规范,一般用这个</h4>
<button @click="datafun3(1)" type="button" class="btn btn-primary">get params传参规范测试</button>
<ul v-for="item,index in arr3" :key="index">
<li><span>id:</span>{{item.id}}</li>
<li><span>内容:</span>{{item.content}}</li>
</ul>
</div>
<div class="a">
<h4>方式四1:get并发请求spread</h4>
<button @click="datafun4all()" type="button" class="btn btn-success">get并发请求spread</button>
<p>{{msg4_1}}</p>
<p>{{msg4_2}}</p>
</div>
<div class="a">
<h4>方式四2:get并发请求all</h4>
<button @click="datafun4all2()" type="button" class="btn btn-success">get并发请求all</button>
<p>{{msg4_3}}</p>
<p>{{msg4_4}}</p>
</div>
</div>
</template>
<script>
export default {
name: 'gettest',
data() {
return {
msg0:"",
msg1:"",
msg2:"",
arr3:[],
msg4_1:{},
msg4_2:"",
msg4_3:"",
msg4_4:"",
}
},
created(){
// this.datafun(1)
// 如果不用按钮调用,也可以created里调用,在页面加载时就会执行.
// console.log($)
},
methods:{
// 【Get 方式不传参:】
func(){
var that=this;
this.$axios.get("http://127.0.0.1:8000/index/")
.then(function(data){
that.msg0=data["data"]
}).catch(function(error){
alert(error)
})
},
datafun1(){
var that=this;//axios里面的this就不是本意了,需在外面得到本意this
// 【Get传参一:】本句直接问号传参,与后台id对应
this.$axios.get("http://127.0.0.1:8000/get1/?id=1")
.then(function(data){
// 记住$axios里面用that
that.msg1=data["data"].content
})
},
datafun2(){
var that=this;
// 【Get传参二:与1的区别就是params传参】
this.$axios.get("http://127.0.0.1:8000/get1/",{
// 本句传参
params: {
id: 2
}
}).then(function(data){
that.msg2=data["data"].content
console.log(data)
})
},
// params传参,写的规范,一般用这个
datafun3:function(id){
console.log(1111)
var that=this;
this.$axios({
method:'get',
url:'http://127.0.0.1:8000/get3list/',
params:{
id:id
}
}).then(function(data){
that.arr3=data.data
});
},
//分界线。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
// get4
//【Get执行多个并发请求 一:】:spread()方法
// 调用时调用:datafun4all
getfun1:function(){
return this.$axios.get("http://127.0.0.1:8000/get1/?id=1")
},
getfun2:function(){
return this.$axios.get("http://127.0.0.1:8000/get1/?id=2")
},
datafun4all:function(){
var that=this;
this.$axios.all([that.getfun1(),that.getfun2()]).then(
that.$axios.spread(function(get1,get2){
that.msg4_1=get1.data;
that.msg4_2=get2.data.content;
})
)
},
//分界线。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
//【Get执行多个并发请求 二:】:all()方法 //不要忘了调用
datafun4all2:function(){
var that=this;
that.$axios.all([
that.$axios.get('http://127.0.0.1:8000/get1/?id=3'),
that.$axios.get('http://127.0.0.1:8000/get1/?id=4')
]).then(that.$axios.spread(function (user1, user2) {
that.msg4_3=user1.data.content
that.msg4_4=user2.data.content
}))
},
}
}
</script>
<style scoped="scoped">
.a{
border: skyblue solid 3px;
width: 500px;
margin: 10px auto;
margin:
}
</style>
python后台数据:
views页面:
from django.shortcuts import render
from django.http import HttpResponse
# 专为vue学习axios 准备的后台代码 hbuilder: vue3demo3-->src-->conponents-->axios
# 启动:找到d:/ajax/worktwo/worktwo,在pacharm打开,执行 python manage.py runserver
# urls在worktwo文件夹,想换app可以换
# axios get不传参
def index(request,response=None):
response = HttpResponse("哈哈哈哈")
response["Access-Control-Allow-Origin"] = "*"
return response
# axios get传参
def get1(request, response=None):
_index = request.GET.get("id")
if _index == "1":
response = HttpResponse('{"id":1,"content":"手机的内容"}')
elif _index == "2":
response = HttpResponse('{"id":2,"content":"ipad的内容"}')
elif _index == "3":
response = HttpResponse('{"id":3,"content":"笔记本的内容"}')
elif _index == "4":
response = HttpResponse('{"id":4,"content":"电视的内容"}')
elif _index == "5":
response = HttpResponse('{"id":5,"content":"冰箱的内容"}')
elif _index == "6":
response = HttpResponse('{"id":6,"content":"空调的内容"}')
elif _index == "7":
response = HttpResponse('{"id":7,"content":"帽子的内容"}')
elif _index == "8":
response = HttpResponse('{"id":8,"content":"大衣的内容"}')
else:
response = HttpResponse('{"id":9,"content":"鞋子的内容"}')
response["Access-Control-Allow-Origin"] = "*"
return response
urls:
from django.contrib import admin
from django.urls import path
from vue3demo2 import views
urlpatterns = [
path('admin/', admin.site.urls),
# vue3demo2的 :axios get传值
path('index/', views.index),
path('get1/', views.get1),
path('get3list/', views.get3list),
# post传值
path('post1/', views.post1),
]
展示效果:


三、post请求
vue页面:posttest.vue
<template>
<div>
<h3>下面是axios的使用方法:POST方式 </h3>
<div class="a">
<h4>方式一:单个参数</h4>
<button @click="func1()" type="button" class="btn btn-primary">1测试按钮</button>
<p>{{ message1}}</p>
</div>
<div class="a">
<h4>方式二1:多个参数</h4>
<button @click="func2()" type="button" class="btn btn-primary">2测试按钮</button>
<p>{{ message2}}</p>
</div>
<div class="a">
<h4>方式二2:多个参数,数组,对象作为参数</h4>
<button @click="func22()" type="button" class="btn btn-primary">22数组对象测试按钮</button>
<p>{{ message22}}</p>
</div>
<div class="a">
<h4>方式三:</h4>
<button @click="func3()" type="button" class="btn btn-primary">3测试按钮</button>
<p>{{ message3}}</p>
</div>
</div>
</template>
<script>
// 第三种方式需导入qs插件,这样可兼容IE浏览器
import Qs from 'qs'
//导出插件
export default{
name:'posttest',
data:function(){
return{
message1:"",
message2:"",
message22:"",
message3:"",
// post
post22arr:[2,"猫",{"id":1,"name":"小明"}],
post22obj:{"id":1,"name":"小明","arr":[1,2]},
}
},
created:function(){
// 可以在created初始化
// this.func1()
// this.func2()
// this.func3()
},
methods:{
// POST传输的方式一
func1:function(){
var that=this
var params = new URLSearchParams();
// 此句为传参 键值对方式传参 ,单个传参,也可以传多个参数
params.append('id',7);
that.$axios.post("http://127.0.0.1:8000/post1/",params)
.then(function(data){
that.message1=data["data"]
console.log(data)
}).catch(function(error){
console.log(error)
})
},
// POST传输的方式二 规范写法。一般用这个
//可以传多个参数 id和password
//post传输方式1和2一样。
func2:function(){
var that=this;
var params = new URLSearchParams();
params.append('id',7);
params.append('password','123456');
// 发起一个post请求
that.$axios({
method:'post',
url:'http://127.0.0.1:8000/post1/',
data:params
}).then(function(data){
that.message2=data.data
});
},
// POST传输的方式二 .2 也可以传数组,对象作为参数。 后台 post22
func22:function(){
var that=this;
var params = new URLSearchParams();
// 注意传对象的时候,要用window.JSON转成json格式,python要接收json格式.
params.append('post22arr', window.JSON.stringify(that.post22arr));
params.append('post22obj', window.JSON.stringify(that.post22obj));
// 发起一个post请求
that.$axios({
method:'post',
url:'http://127.0.0.1:8000/post22/',
data:params
}).then(function(data){
that.message22=data.data
});
},
// POST传输的方式三 把参数变成&分割的, 需要在本页面导入qs
func3:function(){
var that=this;
var _data={
id:8 //此句传参
};
var sendJson=Qs.stringify(_data); //qs
that.$axios({
method:'post',
url:'http://127.0.0.1:8000/post1/',
data:sendJson //stringify
}).then(function(data){
that.message3=data.data.content
});
},
}
}
</script>
<style scoped>
p{
background-color: lightblue;
height: 30px;
text-align: center;
}
.msg{
background-color: skyblue;
}
.a{
border: skyblue solid 3px;
width: 500px;
margin: 10px auto;
margin:
}
</style>
post 数组/对象作为参数详解:
传数组和对象的时候,可以看到,我的数组里包着对象,对象里也包含数组,相当于二维的数组或对象,不管是一维的还是二维的,这个时候我们一定要先用json.stringify(),转换一下,再传入后端,因为django接收的是json字符串。
在用post传数组和对象的时候,网上的教程都是用qs,我用qs四种方式都没做出来,可能是我后台接收的格式没有弄好或者我的数组是二维的。类型和格式一直有问题,qs是把你的数组转换成url?ids=1&ids=2&id=3,这种形式,我觉得还是要看你的后台需要接收什么类型的数据,前端就传什么类型。
qs:
axios.post(url, qs.stringify(
params: {
ids: [1,2,3],
type: 1
}, { indices: false })
)
python后台的post数据
# axios post
def post1(request, response=None):
_index = request.POST.get("id")
# //func2 多参数传参
pwd= request.POST.get("password")
print(pwd)
if _index == "1":
response = HttpResponse('{"id":1,"content":"手机的内容"}')
elif _index == "2":
response = HttpResponse('{"id":2,"content":"ipad的内容"}')
elif _index == "3":
response = HttpResponse('{"id":3,"content":"笔记本的内容"}')
elif _index == "4":
response = HttpResponse('{"id":4,"content":"电视的内容"}')
elif _index == "5":
response = HttpResponse('{"id":5,"content":"冰箱的内容"}')
elif _index == "6":
response = HttpResponse('{"id":6,"content":"空调的内容"}')
elif _index == "7":
response = HttpResponse('{"id":7,"content":"帽子的内容"}')
elif _index == "8":
response = HttpResponse('{"id":8,"content":"大衣的内容"}')
else:
response = HttpResponse('{"id":9,"content":"鞋子的内容"}')
response["Access-Control-Allow-Origin"] = "*"
return response
#数组和对象作为参数
def post22(request, response=None):
arr2 =request.POST.get("post22arr")
print(arr2)# [2,"猫",{"id":1,"name":"小明"}]
print(type(arr2)) #<class 'str'> 传过来的json字符串要转成列表格式,字符串obj转成字典
print(type(arr2.split())) #字符串转列表 <class 'list'>
for i in arr2.split():
print(i)
obj2 = request.POST.get("post22obj")
print("22--obj-")
print(obj2) #{"id":1,"name":"小明","arr":[1,2]}
# obj字符串转成字典 eval(obj)
for key, value in eval(obj2).items():
print(key,value)
# id 1
# arr[1, 2]
# name 小明
# 给前端返回arr2
if arr2:
response = HttpResponse(arr2)
else:
response = HttpResponse('没收到参数!')
response["Access-Control-Allow-Origin"] = "*"
return response
效果:

python控制台
