代碼邏輯介紹
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) 放通後端,前端接收到響應並顯示數據。