- vue本身不支持发送AJAX请求,需要使用vue-resource、axios等插件实现。
- axios是一个基于Promise的HTTP请求客户端,用来发送请求,也是vue2.0官方推荐的,同时不再对vue-resource进行更新和维护。
参考:GitHub上搜索axios,查看API文档
1 login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<span>[[ message ]]</span>
<button @click="login">登录Get</button>
<button @click="login2">登录Post</button>
<hr>
[[ username ]]
</div>
</body>
<script>
var vm = new Vue({
el: "#app",
delimiters: ["[[", "]]"],
data: {
message: "hello",
username: "11",
},
methods: {
login: function() {
var url = "http://127.0.0.1:8000/recv/?username=itcast&password=1234"
axios.get(url).then((response)=>{
console.log(response.data.info.username)
this.username = response.data.info.username
}).catch((err)=>{
console.log(err);
})
},
login2: function() {
url = "http://127.0.0.1:8000/recv/"
axios.post(url, {
"username": "苏轼",
"password": "123456",
}).then((response)=>{
console.log(response.data.info.username)
this.username = response.data.info.username
}).catch((err)=>{
console.log(err);
})
}
}
})
</script>
</html>
1.因为Vue的模板变量和django的模板变量分隔符冲突,所以需要修改Vue的分隔符delimiters:[“[[“,”]]”] 2.箭头函数解决这个指向的问题
2 view.py
from django.shortcuts import render
from django.views import View
from django.http import JsonResponse, HttpRequest
import json
# Create your views here.
class LoginView(View):
def get(self, request):
return render(request, "login.html")
def post(self, request):
...
class RecvView(View):
def get(self, request):
data = request.GET
username = data.get("username")
password = data.get("password")
return JsonResponse({"info": {"username": username}})
def post(self, request: HttpRequest):
data = json.loads(request.body.decode())
username = data.get("username")
password = data.get("password")
return JsonResponse({"info": {"username": username}})