Django環(huán)境下使用Ajax的操作代碼
Django環(huán)境下使用Ajax
介紹
AJAX 的主要目標是在不刷新整個頁面的情況下,通過后臺與服務(wù)器進行數(shù)據(jù)交換和更新頁面內(nèi)容。通過 AJAX,您可以向服務(wù)器發(fā)送請求并接收響應(yīng),然后使用 JavaScript 動態(tài)地更新頁面的部分內(nèi)容
簡單來說就是將后端數(shù)據(jù)進行加工后傳給前端,再利用js對數(shù)據(jù)進行加工或判斷后渲染到前端
AJAX 不需要任何瀏覽器插件,但需要用戶允許JavaScript在瀏覽器上執(zhí)行,AJAX 使用異步交互與服務(wù)器進行通信
- 同步交互:
- 客戶端發(fā)出一個請求后,需要等待服務(wù)器響應(yīng)結(jié)束后,才能發(fā)出第二個請求;
- 異步交互:
- 客戶端發(fā)出一個請求后,無需等待服務(wù)器響應(yīng)結(jié)束,就可以發(fā)出第二個請求。
前情提要
常見的發(fā)送請求方式:
- 瀏覽器地址直接輸入
url回車GET請求
- a標簽的
href屬性GET請求/POST請求
- form表單
GET請求/POST請求
- Ajax
GET請求/POST請求
示例
預(yù)期效果

JS實現(xiàn)
<body>
<input type="text" id="num1">+
<input type="text" id="num2">=<input type="text" id="num3"><br>
<button id="b1">點我計算結(jié)果</button>
<script>
document.getElementById('b1').addEventListener('click', function () {
var num1 = document.getElementById('num1').value
var num2 = document.getElementById('num2').value
var sum = parseInt(num1) + parseInt(num2)
document.getElementById('num3').value = sum
})
</script>
</body>Ajax實現(xiàn)
將要計算的參數(shù)通過data傳遞給后端
再由success接受后端返回的數(shù)據(jù)進行渲染
<body>
<input type="text" id="num1">+
<input type="text" id="num2">=<input type="text" id="num3"><br>
<button id="b1">點我計算結(jié)果</button>
<script>
document.getElementById('b1').addEventListener('click', function () {
var num1 = document.getElementById('num1').value
var num2 = document.getElementById('num2').value
$.ajax({
{#url:指定當前數(shù)據(jù)提交的網(wǎng)址,如果不寫就和form表單的action一樣,默認釋放前路由地址#}
url:'',
{#type:請求類型 GET / POST 默認是GET#}
type:'post',
{#data:傳給后端的數(shù)據(jù)#}
data:{
'num1':num1,
'num2':num2,
},
{#success:回調(diào)函數(shù) 接受后端傳過來的數(shù)據(jù)#}
success:function (data){
console.log(data)
document.getElementById('num3').value = data
}
})
})
</script>
</body>后端接受到data數(shù)據(jù)并返回sum參數(shù)
def test(request):
if request.method == 'POST':
data = request.POST
num1 = data.get('num1')
num2 = data.get('num2')
sum = int(num1) + int(num2)
return HttpResponse(sum)
return render(request, 'app01/test.html', locals())傳遞JSON格式數(shù)據(jù)
success獲取由后端返回的數(shù)據(jù)并使用JSON.parse(data)進行數(shù)據(jù)轉(zhuǎn)換,這樣便可以直接用.屬性獲取參數(shù)JSON.stringify:ajax中將需要傳遞的數(shù)據(jù)轉(zhuǎn)換成json類型json.loads(request.body.decode()):后端接受數(shù)據(jù)時需要通過request.body來獲取請求體,然后loads手動解析json數(shù)據(jù)
<body>
<input type="text" id="num1">+
<input type="text" id="num2">=<input type="text" id="num3"><br>
<button id="b1">點我計算結(jié)果</button>
<script>
document.getElementById('b1').addEventListener('click', function () {
var num1 = document.getElementById('num1').value
var num2 = document.getElementById('num2').value
$.ajax({
{#url:指定當前數(shù)據(jù)提交的網(wǎng)址,如果不寫就和form表單的action一樣,默認釋放前路由地址#}
url: '',
{#type:請求類型 GET / POST 默認是GET#}
type: 'post',
{#data:以json格式傳遞給后端數(shù)據(jù)#}
data: JSON.stringify({
'num1': num1,
'num2': num2,
}),
{#success:回調(diào)函數(shù) 接受后端傳過來的數(shù)據(jù)#}
success: function (data) {
var new_data = JSON.parse(data)
if (new_data.code != 200) {
alert('非法數(shù)據(jù)')
} else {
console.log(data)
document.getElementById('num3').value = new_data.sum
}
}
})
})
</script>
</body>接受數(shù)據(jù)并返回json格式數(shù)據(jù)(主力這里回調(diào)函數(shù)用的是data.參數(shù))
def test(request):
if request.method == 'POST':
# 提取json數(shù)據(jù)必須通過request.body獲取請求體 并手動解析 JSON 數(shù)據(jù)
data = json.loads(request.body.decode())
num1 = data.get('num1')
num2 = data.get('num2')
sum = int(num1) + int(num2)
# HttpResponse發(fā)送給前端的是str對象 需要在success重新轉(zhuǎn)換類型
return HttpResponse(json.dumps({'code':200,'sum':sum}))
return render(request, 'app01/test.html', locals())傳遞文件數(shù)據(jù)
<script>
$(document).ready(
$("#btn_result").click(function () {
let numberOne = $("#number1").val();
let numberTwo = $("#number2").val();
let fileVal = $("#file_input")[0].files[0];
// Ajax攜帶文件數(shù)據(jù)需要借助第三方的 formData對象
// (1)實例化得到一個 form對象
// 將所有的鍵值對數(shù)據(jù)都要放到 form對象中
let formDataObj = new FormData();
formDataObj.append("numberOne", numberOne)
formDataObj.append("numberTwo", numberTwo)
formDataObj.append("file", fileVal)
console.log(fileVal)
console.log(formDataObj)
// 基于Ajax發(fā)送請求
$.ajax({
// url:指定當前數(shù)據(jù)提交的網(wǎng)址,如果不寫就和form表單的action一樣,默認釋放前路由地址
url: "",
// type:請求類型 GET / POST 默認是GET
type: "post",
// data:傳給后端的數(shù)據(jù)
//(1)傳輸?shù)膁ata直接放上面的 form對象即可
data: formDataObj,
//(2)走form對象不能讓他使用編碼對數(shù)據(jù)進行編碼
contentType: false, // 默認編碼是 urlencoded
//(3)告訴瀏覽器不要對數(shù)據(jù)進行額外的處理
processData: false,
{#data: {'number_one': numberOne, "number_two": numberTwo},#}
// success:回調(diào)函數(shù) 接受后端傳過來的數(shù)據(jù)
success: function (data) {
console.log(data)
console.log(typeof (data))
// 使用 js自己的序列化方法序列化數(shù)據(jù)
{#let dataVal = JSON.parse(data)#}
console.log(typeof (data))
if (data.code === 200) {
$("#result").val(data.result)
} else {
alert("非法的數(shù)據(jù)")
}
}
})
})
)
</script>def test(request):
if request.method == "POST":
# 可以用來判斷當前的請求方式是否是Ajax
print(request.is_ajax()) # True
# print(type(request.body.decode("utf-8")[0]))
# 獲取普通的鍵值對數(shù)據(jù)只需要通過 POST方法
data = request.POST
print(data) # <QueryDict: {'numberOne': ['2'], 'numberTwo': ['2']}>
# 獲取form對象中的文件數(shù)據(jù)也要借助 FILES
print(request.FILES) # <MultiValueDict: {'file': [<InMemoryUploadedFile: avatar.jpg (image/jpeg)>]}>
return JsonResponse({"code": 200, "result": "ok"})
return render(request, "app01/test.html", locals())Django自帶的序列化組件
什么是序列化?
就是當我想要從數(shù)據(jù)庫提取出數(shù)據(jù)后將數(shù)據(jù)對象轉(zhuǎn)換為可以直接使用的數(shù)據(jù)的過程
基于jsonresponse序列化數(shù)據(jù)
from app01.models import User
def get_user(request):
# 查詢所有的用戶數(shù)據(jù)
user_data_list = []
# 此時獲取到的是對象數(shù)據(jù)<QuerySet [<Author: Author object (1)>, <Author: Author object (2)>]>
user_queryset = User.objects.all()
# 將數(shù)據(jù)字段提取后裝進列表
for user_obj in user_queryset:
user_data_list.append({
"username": user_obj.username,
"age": user_obj.age,
"gender": user_obj.get_gender_display(),
})
print(user_data_list)
# 將列表返回前端
return JsonResponse(user_data_list,safe=False)[{'username': 'drema', 'age': 18, 'gender': 'female'}, {'username': 'opp', 'age': 28, 'gender': 2}, {'username': 'hope', 'age': 38, 'gender': 'female'}]
基于Django自帶的serializers
需要導(dǎo)入serializers模塊
from app01 import models
from django.core import serializers
def test(request):
author = models.Author.objects.all()
author_list = serializers.serialize("json", author)
print(author_list)
return JsonResponse(user_data_list, safe=False)[{"model": "app01.author", "pk": 1, "fields": {"name": "張三", "age": 11, "gender": 2}}, {"model": "app01.author", "pk": 2, "fields": {"name": "李四", "age": 19, "gender": 2}}]注冊示例
# 前端
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- 引入jQuery-->
<script src="{% static 'js/jquery.js' %}"></script>
<!-- 引入Bootstrap的CSS文件-->
<link href="{% static 'css/bootstrap.min.css' %}" rel="external nofollow" rel="stylesheet">
<!-- 引入Bootstrap的JavaScript文件-->
<script src="{% static 'js/bootstrap.js' %}"></script>
<style>
/* 左側(cè)空白區(qū)域 */
.left-section {
background-color: dimgrey;
width: 25%;
height: 100vh;
position: fixed;
top: 0;
left: 0;
}
/* 右側(cè)空白區(qū)域 */
.right-section {
background-color: dimgrey;
width: 25%;
height: 100vh;
position: fixed;
top: 0;
right: 0;
}
.d1 {
position: fixed;
left: 35%;
}
.form-control:focus {
outline: none;
box-shadow: 0 0 5px cornflowerblue;
}
.btn-default + .btn-primary {
margin-left: 150px; /* 調(diào)整為所需的間距 */
}
</style>
</head>
<body>
<div class="left-section"></div>
<div class="right-section"></div>
<div class="d1">
{# <form action="" method="post">#}
<div class="form-group">
<label for="username">用戶名</label><br>
<input type="text" class="form-control" id="username" placeholder="Username"><br>
<hr>
</div>
<div class="form-group">
<label for="pwd">密碼</label><br>
<input type="password" class="form-control" id="password" placeholder="Password"><br>
<hr>
</div>
<div class="form-group">
<label for="pwd2">再次輸入密碼</label><br>
<input type="password" class="form-control" id="password2" placeholder="Password"><br>
</div>
<button type="reset" class="btn btn-default">重置</button>
<button class="btn btn-primary" id="b1">確認</button>
{# </form>#}
</div>
<script>
var b1 = document.getElementById("b1")
$(document).ready(function () {
b1.addEventListener('click', function () {
$.ajax({
url: '',
type: 'post',
data: JSON.stringify({
'username': document.getElementById("username").value,
'password': document.getElementById("password").value,
'password2': document.getElementById("password2").value
}),
contentType: 'application/json',
success: function (data) {
alert(JSON.parse(data.state))
},
error: () => {
console.log('錯誤')
}
})
})
})
</script>
</body>
</html># 后端
def register(request):
if request.method == 'POST' and request.is_ajax():
# data = request.POST
data = json.loads(request.body.decode())
print(data)
username = data.get('username')
password = data.get('password')
print(username, password)
# models.User.objects.create(username=username,password=password)
state = {'state': 200}
return JsonResponse(state)
return render(request, 'app01/register.html')到此這篇關(guān)于Django環(huán)境下使用Ajax的文章就介紹到這了,更多相關(guān)Django使用Ajax內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
向量化操作改進數(shù)據(jù)分析工作流的Pandas?Numpy示例分析
這篇文章主要介紹了向量化操作改進數(shù)據(jù)分析工作流的Pandas?Numpy示例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-10-10
Python之虛擬環(huán)境virtualenv,pipreqs生成項目依賴第三方包的方法
今天小編就為大家分享一篇Python之虛擬環(huán)境virtualenv,pipreqs生成項目依賴第三方包的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07
pycharm中使用request和Pytest進行接口測試的方法
這篇文章主要介紹了pycharm中使用request和Pytest進行接口測試的方法,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07
Python腳本開發(fā)中的命令行參數(shù)及傳參示例詳解
這篇文章主要為大家介紹了Python腳本開發(fā)中的命令行參數(shù)及傳參示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-07-07
Python3使用pywinauto如何檢測需要獲取程序元素
這篇文章主要為大家詳細介紹了Python3使用pywinauto如何檢測需要獲取程序元素,文中的示例代碼講解詳細,感興趣的小伙伴可以參考一下2025-02-02

