Django 之 JsonResponse 對象


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 前端不用反序列化,只能傳輸字典,不能傳輸字符串。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM