AJAX 是 Asynchronous JavaScript and XML 的縮寫。它不是新的程式語言,而是運用既有標準的一種新方式——在不重新載入整個頁面的前提下,與伺服器交換資料並更新部分畫面。
很多網頁操作其實不需要刷新整頁,這正是 AJAX 存在的意義。在 Django 專案裡,最常見的組合是 jQuery 的 $.ajax() 搭配 Django 視圖,因此第一步先把 jQuery 下載好放進靜態目錄。
先來看最基礎的例子:前端送出一個字串,後端印出來並回應。
views.py:
#coding:utf8
from django.shortcuts import render, HttpResponse, render_to_response
def Ajax(request):
if request.method == 'POST':
print(request.POST)
return HttpResponse('執行成功')
else:
return render_to_response('app03/ajax.html')ajax.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax</title>
</head>
<body>
<input id='name' type='text' />
<input type='button' value='點擊執行 Ajax 請求' onclick='DoAjax()' />
<script src='/static/jquery/jquery-3.2.1.js'></script>
<script type='text/javascript'>
function DoAjax() {
var temp = $('#name').val();
$.ajax({
url: 'app03/ajax/',
type: 'POST',
data: { data: temp },
success: function (arg) {
console.log(arg);
},
error: function () {
console.log('failed');
}
});
}
</script>
</body>
</html>

注意這裡同時寫了 success 與 error 兩個回呼。除錯階段把失敗分支一起寫上,能省下大量猜測時間。
實務上更常需要傳列表、字典這類結構化資料。這時必須先序列化成字串,否則後端收到的格式會跟預期不同——這就是 JSON 派上用場的地方。
views.py:
#coding:utf8
from django.shortcuts import render, HttpResponse, render_to_response
import json
def Ajax(request):
if request.method == 'POST':
print(request.POST)
data = {
'status': 1,
'msg': '請求成功',
'data': ['A', 'B', 'C']
}
return HttpResponse(json.dumps(data))
else:
return render_to_response('app/ajax.html')ajax.html:
<script type='text/javascript'>
function DoAjax() {
var temp = $('#name').val();
$.ajax({
url: 'app03/ajax/',
type: 'POST',
data: { data: temp },
success: function (arg) {
var obj = jQuery.parseJSON(arg);
console.log(obj.status);
console.log(obj.msg);
console.log(obj.data);
$('#name').val(obj.msg);
},
error: function () {
console.log('failed');
}
});
}
</script>

後端用 json.dumps() 把 Python 物件轉成 JSON 字串,前端再用 jQuery.parseJSON() 還原成物件,就能直接以 obj.msg、obj.data 取值。這種「後端回傳結構化包裝物件,前端依欄位取用」的模式,後續幾乎所有 AJAX 互動都建立在它之上。