代码逻辑介绍
ajax/axios发送GET/POST请求->后端处理->返回数据前端页面局部刷新
视图:
views.py
import json
from django.http import JsonResponse
from django.shortcuts import render
# Create your views here.
from django.views import View
class LoginView(View):
def get(self, request):
return render(request, 'login.html')
def post(self, request):
pass
class ReceiveView(View):
def get(self, request):
# 1. 接收参数
data = request.GET
username = data.get('username')
password = data.get('password')
return JsonResponse({'info':{'username':username}})
def post(self, request):
data = json.loads(request.body.decode())
# data = request.POST
print(data)
username = data.get('username')
print(username)
password = data.get('password')
return JsonResponse({'info':{'username':username}})
注意:
使用ajax发送POST请求的时候,后端获取POST参数使用
data = request.POST
使用axios发送POST请求的时候,后端获取POST参数使用。
因为request.body数据格式为:b'{"username":"wuayng","password":"123"}'
data = json.loads(request.body.decode())
路由
urls.py
from django.conf.urls import url
from book import views
urlpatterns = [
url(r'^login/$', views.LoginView.as_view()),
url(r'rece/$', views.ReceiveView.as_view()),
]
模板
axios
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- 1. 导入Vue -->
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
{# 导入axios#}
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<!-- 2. 定义一个标签 需要给一个标签添加id -->
<div id="app">
{# vue的大胡子语法和django/flask的模板语法冲突#}
<span>[[message]]</span>
<button @click="login">登陆</button>
<hr>
[[username]]
<hr>
<button @click="login2">post</button>
</div>
</body>
<!-- 3. 创建Vue实例 -->
<script type="text/javascript">
var vm = new Vue({
el: '#app',
delimiters: ['[[', ']]'],
data: {
message: 'hello',
username: '',
},
methods: {
login: function () {
// {# 这里发送axios#}
var url = 'http://127.0.0.1:8000/rece/?username=wuyang&password=1234'
// {#then catch用箭头函数#}
axios.get(url).then((response) => {
// {#response(响应)--->response.data(返回数据)#}
console.log(response.data.info.username);
this.username = response.data.info.username;
}).catch((error) => {
console.log(error)
})
},
login2:function () {
var url = 'http://127.0.0.1:8000/rece/'
axios.post(url,{
'username':'wuayng',
'password':'123',
}).then((response) => {
console.log(response.data.info.username);
this.username = response.data.info.username;
}).catch((error) => {
console.log(error)
})
},
},
});
</script>
</html>
分析:
(1) index.html中44行和54行打断点,点击登陆按钮,触发GET请求。
然后放通前端
(2) 后端views.py的24行和33行打断点
在确认接收成功前端GET请求参数后,放通后端,发现前端接收到响应并成功显示数据。
(3) 点击post按钮触发POST请求
然后放通前端
(2) 后端接收到axios发送的POST请求,参数在request.bosy中
(3) 放通后端前端接收到响应并展示数据
ajax
index.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="{% static 'jquery-1.12.4.min.js' %}"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#login_btn').click(function(){
$.ajax({
url: "/rece/?username=wuyang&password=12345",
type:"GET",
success:function(data){
console.log(data.info.username);
$('#div1').html(data.info.username);
},
error:function(){
alert('网络异常');
},
async:true
});
});
$('#login2_btn').click(function(){
$.ajax({
url:"/rece/",
type:"POST",
dataType:"JSON",
data:{"username":"wuyang","password":"12345"},
success:function(data){
console.log(data),
$('#div2').html(data.info.username);
},
error:function(){
alert('网络异常');
},
async:true
});
});
});
</script>
</head>
<body>
<button id="login_btn">登陆</button>
<div id="div1"></div>
<hr>
<button id='login2_btn'>post</button>
<div id="div2"></div>
</body>
</html>
区别在于POST参数存放的位置
(1) index.html的29行打断点,点击post按钮触发POST请求后放通前端
(2) 后端接收到POST请求参数,并且发现request.POST中含有POST请求参数,虽然body中也有,但形式为b'username=wuyang&password=12345'。
(3) 放通后端,前端接收到响应并显示数据。