zoukankan      html  css  js  c++  java
  • 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 前端不用反序列化,只能传输字典,不能传输字符串。
  • 相关阅读:
    [转] MathType的灵活运用
    [zz] 模式识别,计算机视觉领域,期刊
    SQL语句 合并列值 将一列的多个值合并成一行
    目标板识别为U盘
    android 事件传递机制
    linux有关文件权限的命令
    linux中的jiffies变量
    分析Android 根文件系统启动过程(init守护进程分析)
    2010年暂订读书目录
    Android Power Management
  • 原文地址:https://www.cnblogs.com/midworld/p/10991994.html
Copyright © 2011-2022 走看看