• Django-前后台的数据交互


    Django 从后台往前台传递数据时有多种方法可以实现。

    最简单的后台是这样的:

    from django.shortcuts import render
    
    def main_page(request):
        return render(request, 'index.html')

    这个就是返回index.html的内容,但是如果要带一些数据一起传给前台的话,该怎么办呢?

    view >> HTML

    这里是这样:后台传递一些数据给html,直接渲染在网页上,不会有什么复杂的数据处理(如果前台要处理数据,那么就传数据给JS处理)

    Django 代码:

    from django.shortcuts import render
    
    def main_page(request):
        data = [1,2,3,4]
        return render(request, 'index.html', {'data': data})

    html使用 {{ }} 来获取数据

    <div>{{ data }}</div>

    可以对可迭代的数据进行迭代:

    {% for item in data%}
    <p>{{ item }}</p>
    {% endfor %}

    该方法可以传递各种数据类型,包括list,dict等等。
    而且除了 {% for %} 以外还可以进行if判断,大小比较等等。具体的用法读者可以自行搜索。

    view >> JavaScript

    如果数据不传给html用,要传给js用,那么按照上文的方式写会有错误。
    需要注意两点:

    1. views.py中返回的函数中的值要用 json.dumps() 处理
    2. 在网页上要加一个 safe 过滤器。

    代码:
    views.py

    # -*- coding: utf-8 -*-
     
    import json
    from django.shortcuts import render
     
    def main_page(request):
        list = ['view', 'Json', 'JS']
        return render(request, 'index.html', {
                'List': json.dumps(list),
            })

    JavaScript部分:

    var List = {{ List|safe }};

    JavaScript Ajax 动态刷新页面

    步骤1:后台数据通过 JSON 序列化成字符串

    注意:1、json是1个字符串

              2、通过json.dumps('xxx') 序列化成 1个字符串的 '字典对象' 

    views.py

    def ajax(request):
        if request.method=='POST':
            print(request.POST)
            data={'status':0,'msg':'请求成功','data':[11,22,33,44]}
            return HttpResponse(json.dumps(data))
        else:
            return render(request,'ajax.html')

    此时tempates 中ajax.html 代码

    此时浏览器返回的数据

    步骤2:前台取出后台序列化的字符串

    方法1:正则表达式 (不推荐)

    方法2:jQuery.parseJSON() ,需要import json
    转换成1个JQuery可识别的字典(对象)   通过 对象. xxx 取值  (推荐)

    views.py序列化:return HttpResponse(json.dumps(data))

    ajax.html 取值:var obj=jQuery.parseJSON(arg)

             console.log(obj.status)

    修改后的tempates 中ajax.html 代码

    <script type='text/javascript'>
        function DoAjax(){
            var temp=$('#na').val()
            $.ajax({
                url:'/ajax/',           //url相当于 form 中的 action
                type:'POST',            //type相当于form 中的 method
                data:{dat:temp},       // data:传人的数据 dat为任意设置的内容,相当于模版中的{author:lee}
                dataType:'json',
                success:function(arg){     //成功执行  console.log() 函数 arg 为HttpResponse 返回的值
                    var obj=jQuery.parseJSON(arg)    //转化成JS识别的对象
                    console.log(obj)          //打印obj
                    console.log(arg)              //json.dumps(data) 序列化后的数据        
                    console.log(obj.status)       //取json.dumps(data)字典的值status
                    console.log(obj.msg)
                    console.log(obj.data)
                    console.log('request.POST 提交成功')
                },
                error:function(){            //失败 
                    console.log('失败')
                }
            });    
        }
    </script>

    此时前台浏览器 显示数据

     

    方法3:content_type='application/json'

    views.py 序列化:return HttpResponse(json.dumps(data),content_type='application/json')

    浏览器F12有变色提示

    或:HttpResponse(json.dumps(data),content_type='type/json')   浏览器F12无变色提示

    ajax.html 取值 arg.xxx

    方法4:使用JsonRespon 包 (最简单)  前台通过 arg.xxx 取值

    views.py 序列化: return JsonResponse(data) 

    ajax.html 取值:arg.xxx

    区别:HttpResponse 需要dumps 
              JsonResponse 不需要dumps

    views.py

    from django.shortcuts import render
    from django.http import JsonResponse
    def ajax(request):
        if request.method=='POST':
            print(request.POST)
            data={'status':0,'msg':'请求成功','data':[11,22,33,44]} #假如传人的数据为一字典
            #return HttpResponse(json.dumps(data))      #原来写法,需要dumps
            return JsonResponse(data)                  #后来写法
        else:
            return render(request,'ajax.html')

    templates 中的 ajax.html

    <script type='text/javascript'>
        function DoAjax(){
            var temp=$('#na').val()
            $.ajax({
                url:'/ajax/',           //url相当于 form 中的 action
                type:'POST',            //type相当于form 中的 method
                data:{dat:temp},       // data:传人的数据 dat为任意设置的内容,相当于模版中的{author:lee}
                dataType:'json',
                success:function(arg){     //成功执行  console.log() 函数 arg 为HttpResponse 返回的值
                    var obj=jQuery.parseJSON(arg)    //转化成JS识别的对象
                    console.log(obj)          //打印obj
                    console.log(arg)              //json.dumps(data) 序列化后的数据        
                    console.log(obj.status)       //取json.dumps(data)字典的值status
                    console.log(obj.msg)
                    console.log(obj.data)
                    console.log('request.POST 提交成功')
                },
                error:function(){            //失败 
                    console.log('失败')
                }
            });    
        }
    </script>
  • 相关阅读:
    jenkins免密添加SSH Servers
    Workman启动失败的解决方法 stream_socket_server() has been disabled for security reasons
    jenkins主从从服务器发布脚本执行成功但总提示失败 FATAL: Remote call on XXXX failed
    mac OS配置用户全局环境变量(设置字符集为UTF8)
    使用 Application Loader提交IPA文件到苹果市场
    IOS使用批处理打包
    Java进阶知识24 Spring对JDBC的支持
    Java进阶知识23 Spring execution 切入点表达式
    Java进阶知识22 Spring的AOP编程
    Java进阶知识21 Spring的代理模式
  • 原文地址:https://www.cnblogs.com/Python-XiaCaiP/p/10186973.html
Copyright © 2020-2023  润新知