本文介绍: 知识量决定了未来能走多远

目录

一、关系

二、使用

(一)data 字典传值

1. JsonResponse

2. HttpResponse

3. 例子

(二)JsonResponse 有一个 safe 参数

(三)前端接收

1. 接收 JsonResponse 回传的值

2. 接收 HttpResponse 回传的值

3. 不分情况

(四)若报错:TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False

原因:

解决:

例子:


一、关系

        JsonResponse 是 HttpResponse 的一个子类

        从1.7版本开始,Django使用内置JsonResponse类。

二、使用

(一)data 字典传值

1. JsonResponse

JsonResponse 的 data 参数是个字典

# JsonResponse
from django.http import JsonResponse
return JsonResponse(mydict

2. HttpResponse

HttpResponse 的 content 参数值必须是引号包裹字符串

比如,用 json.dumps 将 data 值转成JSON字串。

# HttpResponse
import json
return HttpResponse(json.dumps(mydict))

3. 例子

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'

(二)JsonResponse 有一个 safe 参数

safe控制是否只有dict对象可以序列化,默认为 True

safe 设置为True,但是 data数据类型不是 dict ,则抛出一个 TypeError 类型错误

若想对非字典数据(如列表)进行 dumps ,则 safe 设置为 False。

(三)前端接收

1. 接收 JsonResponse 回传的值

使用JsonResponse传值前台ajax收到data需要转JSON.parsedata),直接使用

2. 接收 HttpResponse 回传的值

使用HttpResponse传值需要转JSON.parsedata处理

3. 不分情况

若是不考虑后台采用JsonResponse或者HttpResponse,则前台ajax处理统一属性dataType:’json’。

(四)若报错:TypeError: In order to allow nondict objects to be serialized set the safe parameter to False

原因

        JsonResponse中的参数要求字典,若非字典报错

解决

        ① 传参数为字典。

        ② 设置参数safe=False。

例子

return JsonResponse(result)
# 改为:
return JsonResponse(result, safe=False)

原文地址:https://blog.csdn.net/xiaoxiaoluobogan/article/details/134791638

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_43910.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注