JsonResponse源碼如下:
class JsonResponse(HttpResponse):
"""
An HTTP response class that consumes data to be serialized to JSON.
:param data: Data to be dumped into json. By default only ``dict`` objects
are allowed to be passed due to a security flaw before EcmaScript 5. See
the ``safe`` parameter for more information.
:param encoder: Should be an json encoder class. Defaults to
``django.core.serializers.json.DjangoJSONEncoder``.
:param safe: Controls if only ``dict`` objects may be serialized. Defaults
to ``True``.
"""
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True, **kwargs):
if safe and not isinstance(data, dict):
raise TypeError('In order to allow non-dict objects to be '
'serialized set the safe parameter to False')
kwargs.setdefault('content_type', 'application/json')
data = json.dumps(data, cls=encoder)
super(JsonResponse, self).__init__(content=data, **kwargs)
1: JsonResponse是HttpResponse的子類, 它的默認(rèn)Content-Type被設(shè)置為: application/json
2: 第一個(gè)參數(shù), data應(yīng)該是一個(gè)字典類型, 當(dāng)safe這個(gè)參數(shù)被設(shè)置為:False, 那data可以填入任何能被轉(zhuǎn)換為JSON格式的對(duì)象, 比如list, tuple, set。默認(rèn)的safe參數(shù)是True, 如果你傳入的data數(shù)據(jù)類型不是字典類型, 那么它就會(huì)拋出TypeError的異常憋肖。
3: json_dumps_params參數(shù)是一個(gè)字典因痛,它將調(diào)用json.dumps()方法并將字典中的參數(shù)傳入給該方法。
JsonResponse與HttpResponse的比較
在返回json數(shù)據(jù)時(shí)
1: 如果這樣返回岸更,ajax還需要進(jìn)行json解析
# views.py中
return HttpResponse(json.dumps({"msg": "OK"}))
# index.html
var data = json.parse(data)
console.log(data.msg)
2: 如果這樣返回鸵膏,兩邊都不需要進(jìn)行json的序列化與反序列化,ajax接受的直接是一個(gè)對(duì)象
# views.py
from django.http import JsonResponse
return JsonResponse({"msg": "OK"})
# index.html
console.log(data.msg)