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 前端不用反序列化,只能传输字典,不能传输字符串。
  • 相关阅读:
    由大见小,从治国看企业管理,宜王霸之道
    止语
    VSTS团队浏览器文档相关
    《宇宙浪子》荐
    从《心物一元》到《神无方易无体》
    [导入][Tricks]在线字体测试
    [导入][Internet]Cheat Sheet: Web 2.0
    [导入][Code]Asp.net CSS问题
    一个JSON 实例 jQuery 解析JSON数据
    JQuery ajax 返回值如何进行赋值
  • 原文地址:https://www.cnblogs.com/midworld/p/10991994.html
Copyright © 2011-2022 走看看