目錄
一、關系
二、使用
(一)data 字典傳值
1. HttpResponse
(1)寫法
(2)前端接收 HttpResponse?回傳的值
2. JsonResponse
(1)寫法
(2)前端接收 JsonResponse 回傳的值
3. 特殊數據類型的處理
4. 例子
(二)JsonResponse 有一個 safe 參數
1. safe 作用
2.?若報錯:TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False
(1)原因
(2)解決
一、關系
????????JsonResponse 是 HttpResponse 的一個子類。
? ? ? ? 從1.7版本開始,Django使用內置JsonResponse類。
二、使用
(一)data 字典傳值
1. HttpResponse
(1)寫法
HttpResponse 的 content 參數值必須是引號包裹的字符串。
比如,若 data 參數值是個對象(字典),則用 json.dumps 將 data 值轉成JSON字串。
# HttpResponse
import json
return HttpResponse(json.dumps(mydict))
(2)前端接收 HttpResponse?回傳的值
因為,HttpResponse傳的值是通過json處理后的字串格式。所以,前端ajax收到的data是json字串格式,需要用JSON.parse(data)處理,去除json字串。
2. JsonResponse
(1)寫法
JsonResponse 的 data 參數可以是個對象(字典)。
# JsonResponse
from django.http import JsonResponse
return JsonResponse(mydict)
(2)前端接收 JsonResponse 回傳的值
因為,JsonResponse傳的值是字典,沒有經過json處理。所以,前端可以不用JSON.parse(data)處理,直接使用。
3. 特殊數據類型的處理
????????若是queryset類型的列表,可以先利用列表生成式轉換成陣列,再傳給前端。
# JsonResponse
from django.http import JsonResponse
myqst = models.Book.objects.filter(booktype='文藝類').values_list('name', flat=True)
mylist = [m for m in myqst]
return JsonResponse(mylist)
4. 例子
import json
from django.http import JsonResponse
data= {'name': '蘿卜干'}# 第一種
HttpResponse(json.dumps(data), content_type='application/json') # 第一個參數位置,默認是content的參數值,第二個位置需要指定是什么參數的值,比如content_type=XXX# 第二種(幾乎等價于第一種)
JsonResponse(data) # 默認的content_type='application/json'
?json相關知識可參考另一篇文章:Backend - Python 序列化-CSDN博客
(二)JsonResponse 有一個 safe 參數
1. safe 作用
????????默認為 True,控制JsonResponse中只有dict對象可以序列化。
2.?若報錯:TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False
(1)原因
????????JsonResponse中的safe參數為True,要求data值類型必須為字典,若非字典則拋出一個 TypeError 類型錯誤。??
(2)解決
? ? ? ? 方法① 傳data參數為字典類型。
? ? ? ? 方法② 若想傳列表List類型等,則設置參數safe=False。如下面代碼:
return JsonResponse(result)
# 改為:
return JsonResponse(result, safe=False)