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

目录

一、关系

二、使用

(一)data 字典传值

1. JsonResponse


        JsonResponse 是 HttpResponse 的一个子类

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

JsonResponse 的 data 参数是个字典

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

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

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

# HttpResponse
import json
return HttpResponse(json.dumps(mydict))
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'

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

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

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

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

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

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

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

        ① 传参数为字典。

        ② 设置参数safe=False。

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

发表回复

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