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 前端不用反序列化,只能传输字典,不能传输字符串。
  • 相关阅读:
    Service(服务)简单使用
    Android设计模式——抽象工厂方法模式
    Android设计模式——工厂方法模式
    算法问题——递归算法
    Android设计模式——Builder(建造者)模式
    Android设计模式——单例模式
    蓝牙4.0权限问题
    Android 网络状态变化的监听
    RecyclerView的使用
    函数参数的引用传递与值传递
  • 原文地址:https://www.cnblogs.com/midworld/p/10991994.html
Copyright © 2011-2022 走看看