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

JS實(shí)現(xiàn)
<body>
<input type="text" id="num1">+
<input type="text" id="num2">=<input type="text" id="num3"><br>
<button id="b1">點(diǎn)我計(jì)算結(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實(shí)現(xiàn)
將要計(jì)算的參數(shù)通過(guò)data傳遞給后端
再由success接受后端返回的數(shù)據(jù)進(jìn)行渲染
<body>
<input type="text" id="num1">+
<input type="text" id="num2">=<input type="text" id="num3"><br>
<button id="b1">點(diǎn)我計(jì)算結(jié)果</button>
<script>
document.getElementById('b1').addEventListener('click', function () {
var num1 = document.getElementById('num1').value
var num2 = document.getElementById('num2').value
$.ajax({
{#url:指定當(dāng)前數(shù)據(jù)提交的網(wǎng)址,如果不寫(xiě)就和form表單的action一樣,默認(rèn)釋放前路由地址#}
url:'',
{#type:請(qǐng)求類型 GET / POST 默認(rèn)是GET#}
type:'post',
{#data:傳給后端的數(shù)據(jù)#}
data:{
'num1':num1,
'num2':num2,
},
{#success:回調(diào)函數(shù) 接受后端傳過(guò)來(lái)的數(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)進(jìn)行數(shù)據(jù)轉(zhuǎn)換,這樣便可以直接用.屬性獲取參數(shù)JSON.stringify:ajax中將需要傳遞的數(shù)據(jù)轉(zhuǎn)換成json類型json.loads(request.body.decode()):后端接受數(shù)據(jù)時(shí)需要通過(guò)request.body來(lái)獲取請(qǐng)求體,然后loads手動(dòng)解析json數(shù)據(jù)
<body>
<input type="text" id="num1">+
<input type="text" id="num2">=<input type="text" id="num3"><br>
<button id="b1">點(diǎn)我計(jì)算結(jié)果</button>
<script>
document.getElementById('b1').addEventListener('click', function () {
var num1 = document.getElementById('num1').value
var num2 = document.getElementById('num2').value
$.ajax({
{#url:指定當(dāng)前數(shù)據(jù)提交的網(wǎng)址,如果不寫(xiě)就和form表單的action一樣,默認(rèn)釋放前路由地址#}
url: '',
{#type:請(qǐng)求類型 GET / POST 默認(rèn)是GET#}
type: 'post',
{#data:以json格式傳遞給后端數(shù)據(jù)#}
data: JSON.stringify({
'num1': num1,
'num2': num2,
}),
{#success:回調(diào)函數(shù) 接受后端傳過(guò)來(lái)的數(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ù)必須通過(guò)request.body獲取請(qǐng)求體 并手動(dòng)解析 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對(duì)象 需要在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對(duì)象
// (1)實(shí)例化得到一個(gè) form對(duì)象
// 將所有的鍵值對(duì)數(shù)據(jù)都要放到 form對(duì)象中
let formDataObj = new FormData();
formDataObj.append("numberOne", numberOne)
formDataObj.append("numberTwo", numberTwo)
formDataObj.append("file", fileVal)
console.log(fileVal)
console.log(formDataObj)
// 基于Ajax發(fā)送請(qǐng)求
$.ajax({
// url:指定當(dāng)前數(shù)據(jù)提交的網(wǎng)址,如果不寫(xiě)就和form表單的action一樣,默認(rèn)釋放前路由地址
url: "",
// type:請(qǐng)求類型 GET / POST 默認(rèn)是GET
type: "post",
// data:傳給后端的數(shù)據(jù)
//(1)傳輸?shù)膁ata直接放上面的 form對(duì)象即可
data: formDataObj,
//(2)走form對(duì)象不能讓他使用編碼對(duì)數(shù)據(jù)進(jìn)行編碼
contentType: false, // 默認(rèn)編碼是 urlencoded
//(3)告訴瀏覽器不要對(duì)數(shù)據(jù)進(jìn)行額外的處理
processData: false,
{#data: {'number_one': numberOne, "number_two": numberTwo},#}
// success:回調(diào)函數(shù) 接受后端傳過(guò)來(lái)的數(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":
# 可以用來(lái)判斷當(dāng)前的請(qǐng)求方式是否是Ajax
print(request.is_ajax()) # True
# print(type(request.body.decode("utf-8")[0]))
# 獲取普通的鍵值對(duì)數(shù)據(jù)只需要通過(guò) POST方法
data = request.POST
print(data) # <QueryDict: {'numberOne': ['2'], 'numberTwo': ['2']}>
# 獲取form對(duì)象中的文件數(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自帶的序列化組件
什么是序列化?
就是當(dāng)我想要從數(shù)據(jù)庫(kù)提取出數(shù)據(jù)后將數(shù)據(jù)對(duì)象轉(zhuǎn)換為可以直接使用的數(shù)據(jù)的過(guò)程
基于jsonresponse序列化數(shù)據(jù)
from app01.models import User
def get_user(request):
# 查詢所有的用戶數(shù)據(jù)
user_data_list = []
# 此時(shí)獲取到的是對(duì)象數(shù)據(jù)<QuerySet [<Author: Author object (1)>, <Author: Author object (2)>]>
user_queryset = User.objects.all()
# 將數(shù)據(jù)字段提取后裝進(jìn)列表
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}}]注冊(cè)示例
# 前端
{% 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">確認(rèn)</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('錯(cuò)誤')
}
})
})
})
</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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Django使用AJAX調(diào)用自己寫(xiě)的API接口的方法
- Django 使用Ajax進(jìn)行前后臺(tái)交互的示例講解
- Django中使用jquery的ajax進(jìn)行數(shù)據(jù)交互的實(shí)例代碼
- 使用Python的Django框架結(jié)合jQuery實(shí)現(xiàn)AJAX購(gòu)物車頁(yè)面
- django使用ajax post數(shù)據(jù)出現(xiàn)403錯(cuò)誤如何解決
- django中使用jquery ajax post數(shù)據(jù)出現(xiàn)403錯(cuò)誤的解決辦法(兩種方法)
- Django框架如何使用ajax的post方法
相關(guān)文章
Python+Paramiko編寫(xiě)簡(jiǎn)單的SFTP文件上傳下載工具類
Paramiko 是 Python 中最流行的 SSH2 協(xié)議實(shí)現(xiàn)庫(kù),基于它我們可以輕松實(shí)現(xiàn) SFTP 客戶端功能,本文將分享一個(gè)封裝好的 SftpClient 類,支持文件上傳、下載,感興趣的小伙伴可以了解下2026-01-01
Python中關(guān)鍵字nonlocal和global的聲明與解析
這篇文章主要給大家介紹了關(guān)于Python中關(guān)鍵字nonlocal和global的聲明與解析的相關(guān)資料,文中介紹的非常詳細(xì),相信對(duì)大家具有一定的參考價(jià)值,需要的朋友們下面來(lái)一起看看吧。2017-03-03
Python OpenCV對(duì)圖像像素進(jìn)行操作
大家好,本篇文章主要講的是Python OpenCV對(duì)圖像像素進(jìn)行操作,感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話記得收藏一下,方便下次瀏覽2022-01-01
自定義Django_rest_framework_jwt登陸錯(cuò)誤返回的解決
這篇文章主要介紹了自定義Django_rest_framework_jwt登陸錯(cuò)誤返回的解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
pyinstaller打包xgboost項(xiàng)目,得到的可執(zhí)行文件運(yùn)行出錯(cuò)問(wèn)題及解決
文章介紹了使用PyInstaller打包包含XGBoost項(xiàng)目的Python程序時(shí)遇到的錯(cuò)誤,錯(cuò)誤原因是PyInstaller將XGBoost的`sklearn.py`模塊誤認(rèn)為是`scikit-learn`庫(kù),導(dǎo)致找不到`get_params`函數(shù),解決方法是將`sklearn.py`重命名為`sklearn_xgb.py`,以避免命名沖突2026-01-01
Python+OpenCV數(shù)字圖像處理之ROI區(qū)域的提取
ROI區(qū)域又叫感興趣區(qū)域。在機(jī)器視覺(jué)、圖像處理中,從被處理的圖像以方框、圓、橢圓、不規(guī)則多邊形等方式勾勒出需要處理的區(qū)域,稱為感興趣區(qū)域,ROI。本文主要為大家介紹如何通過(guò)Python+OpenCV提取ROI區(qū)域,需要的朋友可以了解一下2021-12-12

