Django JSonResponse對象的實現(xiàn)
更新時間:2023年03月23日 09:21:47 作者:風(fēng)老魔
本文主要介紹了Django JSonResponse對象的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
JsonResponse 是 HttpResponse 的子類,與父類的區(qū)別在于:
- JsonResponse 默認(rèn) Content-Type 類型為 application/json
- HttpResponse 默認(rèn)為 application/text
class JsonResponse(HttpResponse): ? ? def __init__(self, data, encoder=DjangoJSONEncoder, safe=True, ? ? ? ? ? ? ? ? ? ? json_dumps_params=None, **kwargs):
HttpResponse
HttpResponse 每次將數(shù)據(jù)返回給前端需要用 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); ? ? ? # 請求成功
? ? }
})總結(jié)
- HTTPResponse 后端要用 json 模塊序列化,前端也要反序列化。
- JSonResponse 前端不用反序列化,只能傳輸字典,不能傳輸字符串。
到此這篇關(guān)于Django JSonResponse對象的實現(xiàn)的文章就介紹到這了,更多相關(guān)Django JSonResponse對象內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
jmeter中用python實現(xiàn)請求參數(shù)的隨機(jī)方式
首先,需下載Jython插件于https://www.jython.org/download后,將其放入JMeter的lib目錄并重啟JMeter,其次,添加JSR223PreProcessor并選擇Python作為語言,編寫腳本,其中metrics_ids3和metrics_weidu3為列表變量2024-10-10
Python Pandas常用函數(shù)方法總結(jié)
今天給大家?guī)淼氖顷P(guān)于Python的相關(guān)知識,文章圍繞著Pandas常用函數(shù)方法展開,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下2021-06-06

