功能說明:
Ajax請求接口,Django框架下從該接口接收Ajax發送的json數據,同時將新的json數據返回給Ajax,Ajax收到後在js進行處理,然後和頁面內容交互。整個數據前後端交互全部採用json格式。
運行環境:
後端:python3.7、Django2.2
前端:html+js+jquery3.1.1
全部代碼:
urls.py:完成在Django框架下的url映射
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from . import view
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^$', view.show), # 頁面展示
url(r'^process$', view.process), # ajax請求接口
]
view.py:後端的處理函數(顯示頁面與ajax接口)
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.shortcuts import render
from django.http import JsonResponse
def show(request):
return render(request, 'show.html')
def process(request):
if request.is_ajax():
print(request.POST)
data = {
'name': "candy",
'age': 13,
}
list = ['a', 'b', 'c', 'd']
response = JsonResponse({"status": '服務器接收成功', 'data': data, 'list': list})
return response
show.html:前端頁面(包含js和ajax請求代碼)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form >
{% csrf_token %}
First name: <input type="text" name="fname" id="fname"><br>
Last name: <input type="text" name="lname" id="lname"><br>
<input type="button" value="提交" id="upload">
</form>
<p id="p1">Hello World!</p>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
$(function () {
{#一直使用Ajax上傳#}
console.log('Ajax上傳');
$("#upload").click(function () {
var formdata = new FormData();
formdata.append("fname", $("#fname").val());
formdata.append("lname", $("#lname").val());
formdata.append("csrfmiddlewaretoken", $("[name='csrfmiddlewaretoken']").val());
$.ajax({
url: "/process",
type: "post",
data: formdata,
contentType: false,
processData: false,
success: function (data) {
alert("上傳成功!")
console.log(data)
document.getElementById("p1").innerHTML=data.status;
document.getElementById("fname").value=data.data.name;
document.getElementById("lname").value=data.data.age;
alert(data.list)
},
error: function (data) {
alert("上傳失敗!")
console.log(data)
}
})
})
});
</script>
</body>
</html>
結果演示:
提交數據:
點擊提交按鈕:
點擊確定後:
後端打印出接收數據:
本代碼具備良好的拓展性,可直接遷移到任何項目中使用,作爲示例,這裏展示了幾種數據格式直接封裝在json中,傳給前端後,我們可以直接在調試窗口看到數據,同時將其中的幾部分內容分別顯示到頁面內容上,給input輸入框賦值,使用彈框提示內容。
幾點說明:
1、在django中使用JsonResponse()函數能夠直接將json數據發送給前端,前端在js接收後不需要解碼之類的操作,直接使用點操作運算符就能訪問json數據的內容。
2、關於{% csrf_token %}的說明:這是Django 提供的 CSRF 防護機制
django 第一次響應來自某個客戶端的請求時,會在服務器端隨機生成一個 token,把這個 token 放在 cookie 裏。然後每次 POST 請求都會帶上這個 token,這樣就能避免被 CSRF 攻擊。
在本例中,我們在form表單中加入了“{% csrf_token %}”語句,並在頁面js中使用
formdata.append("csrfmiddlewaretoken", $("[name='csrfmiddlewaretoken']").val());
這一條js語句將token值添加到json數據中傳給了後端,在pycharm的打印窗口也能看到。
3、在form表單中,提交按鈕要這樣書寫:
<input type="button" value="提交" id="upload">
type類型一般都爲submit,但此時,雖然仍可以出發Ajax上傳數據,但是同時這個提交按鈕還具有表單提交的動作,即使在form的屬性中沒有定義action和method,此時當我們上傳數據後,頁面會重新刷新,導致無法獲取到後端給我們的數據了。因此這裏要把type變爲button,在前端樣式上其實沒有什麼區別,另外在通過Ajax交互時,可以不再使用from標籤了。
4、在後端的處理中,我們使用
return render(request, 'index.html', {'data': data})
來返回數據時,雖然能夠接收到數據,但是第一存在格式問題,需要更復雜的處理,較爲麻煩;第二中文字符全部變爲了十六進制表示格式。
5、當我們使用Django將數據附帶在頁面中傳給前端時,需要使用json.dumps()處理,在前端的js中也需要加入safe過濾器。例如:
# -*- coding: utf-8 -*-
import json
from django.shortcuts import render
def main_page(request):
list = ['view', 'Json', 'JS']
return render(request, 'index.html', {
'List': json.dumps(list),
})
在前端頁面的js中使用時有:
var List = {{ List|safe }};
代碼全部工程文件下載:
點我下載:https://download.csdn.net/download/ximerr/11135664
參考文獻:
1、Django 前後臺的數據傳遞 :
https://www.cnblogs.com/psklf/archive/2016/05/30/5542612.html
2、Django 的 CSRF 保護機制:
https://www.cnblogs.com/lins05/archive/2012/12/02/2797996.html