JsonResponse 是 HttpResponse 的子類,與父類的區別在於:
- JsonResponse 默認
Content-Type
類型為application/json
- HttpResponse 默認為
application/text
class JsonResponse(HttpResponse):
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
json_dumps_params=None, **kwargs):
HttpResponse
HttpResponse 每次將數據返回給前端需要用 json
模塊序列化,且前端也要反序列化:
# views.py
import json
def index(request):
message = '請求成功'
# ret = {'message': '請求成功'}
return HttpResponse(json.dumps(message)) # 序列化
# index.html
$.ajax({
url: '/accounts/ajax/',
type: 'post',
data: {
'p': 123,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
# 反序列化,或使用 json.parse(arg)
dataType: "JSON",
success: function (arg) {
console.log(arg.message);
}
})
JsonResponse
JsonResponse 只能序列化字典格式,不能序列化字符串,且前端不用反序列化:
from django.http import JsonResponse
def index(request):
ret = {'message': '請求成功'}
return JsonResponse(ret) # 序列化
# index.html
$.ajax({
url: '/accounts/ajax/',
type: 'post',
data: {
'p': 123,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
# 不需要反序列化
# dataType: "JSON",
success: function (arg) {
console.log(arg.message); # 請求成功
}
})
總結
- HTTPResponse 后端要用 json 模塊序列化,前端也要反序列化。
- JSonResponse 前端不用反序列化,只能傳輸字典,不能傳輸字符串。