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 前端不用反序列化,只能传输字典,不能传输字符串。
  • 相关阅读:
    Mac上如何用命令行修改proxy设置
    Mac上解决访问github慢问题
    Bootstrap布局
    ListView详解
    sql server命名规范
    表的管理与操作
    常用编程技巧和方法
    有联系的jQuery选择器
    sql基础查询语句
    数值特征
  • 原文地址:https://www.cnblogs.com/midworld/p/10991994.html
Copyright © 2011-2022 走看看