• CMDB 后台管理之定制界面显示(jquery、ajax)


    需求分析与功能实现

    1、界面展示数据定制化的,通过在服务端views.py中配置 table_config 来自定义要展示的数据

    2、采用jQuery ajax 异步数据请求、处理、展示

    3、请求数据的定制化展示,增加删除、编辑等操作项

    4、jQuery ajax 封装成通用的 js 框架,展示不同数据传入url 参数即可

    5、有些数据只查询不展示(id),有些数据例如device_type_id(设备类型id) 不展示,只展示其对应的设备类型。

    views.py 服务数据展示

    class JsonCustomEncoder(json.JSONEncoder):
    
        def default(self, value):
            if isinstance(value, datetime):
                return value.strftime('%Y-%m-%d %H:%M:%S')
            elif isinstance(value, date):
                return value.strftime('%Y-%m-%d')
            else:
                return json.JSONEncoder.default(self, value)
    
    # Create your views here.
    
    def curd(request):
        # v = models.Server.objects.all()
        return render(request, 'curd.html')
    
    
    def curd_json(request):
        table_config = [
            {
                'q': 'id',
                'title': 'ID',
                'display': False,
                'text': {
                    'tpl': "{n1}",
                    'kwargs': {'n1': '@id'}
                }
            },
            {
                'q': 'hostname',
                'title': '主机名',
                'display': True,
                'text': {
                    'tpl': "{n1}-{n2}",
                    'kwargs': {'n1': '@hostname', 'n2': '@id'}
                }
            },
            # 页面显示:标题:操作;删除,编辑:a标签
            {
                'q': None,
                'title': '操作',
                'display': True,
                'text': {
                    'tpl': "<a href='/del?nid={nid}'>删除</a>",
                    'kwargs': {'nid': '@id'}
                }
            },
        ]
        # 普通值:原值存放即可
        # @值  : 根据id,根据获取当前行对应数据
        values_list = []
        for row in table_config:
            if not row['q']:
                continue
            values_list.append(row['q'])
    
        server_list = models.Server.objects.values(*values_list)
    
        ret = {
            'server_list': list(server_list),
            'table_config': table_config
        }
    
        return HttpResponse(json.dumps(ret, cls=JsonCustomEncoder))
    View Code

    views.py  资产数据展示

    def asset(request):
        # v = models.Server.objects.all()
        return render(request, 'asset.html')
    
    
    def asset_json(request):
        table_config = [
            {
                'q': 'id',
                'title': 'ID',
                'display': False,       #False 时只查询数据不显示在页面
                'text': {
                    'tpl': "{n1}",
                    'kwargs': {'n1': '@id'}
                }
            },
            {
                'q': 'device_type_id',    #通过设备类型id 在字典 device_type_choices中找到对应设备类型
                'title': '资产类型',
                'display': True,
                'text': {
                    'tpl': "{n1}",
                    'kwargs': {'n1': '@@device_type_choices'}       #通过资产类型的id 查询资产类型
                }
            },
            {
                'q': 'device_status_id',
                'title': '状态',
                'display': True,
                'text': {
                    'tpl': "{n1}",
                    'kwargs': {'n1': '@@device_status_choices'}     #通过资产状态id 查询资产状态
                }
            },
            {
                'q': 'cabinet_num',
                'title': '机柜号',
                'display': True,
                'text': {
                    'tpl': "{n1}",
                    'kwargs': {'n1': '@cabinet_num'}
                }
            },
            {
                'q': 'idc__name',
                'title': '机房',
                'display': True,
                'text': {
                    'tpl': "{n1}",
                    'kwargs': {'n1': '@idc__name'}
                }
            },
            # 页面显示:标题:操作;删除,编辑:a标签
            {
                'q': None,
                'title': '操作',
                'display': True,
                'text': {
                    'tpl': "<a href='/del?nid={nid}'>删除</a>",
                    'kwargs': {'nid': '@id'}                        #通过资产id 对资产进行删除等操作
                }
            },
        ]
        # 普通值:原值存放即可
        # @值  : 根据id,根据获取当前行对应数据
        values_list = []
        for row in table_config:
            if not row['q']:
                continue
            values_list.append(row['q'])
    
        server_list = models.Asset.objects.values(*values_list)
    
        ret = {
            'server_list': list(server_list),
            'table_config': table_config,
            'global_dict':{
                'device_type_choices': models.Asset.device_type_choices,
                'device_status_choices': models.Asset.device_status_choices
            }
        }
    
        return HttpResponse(json.dumps(ret, cls=JsonCustomEncoder))
    View Code

    asset.html 页面代码

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
        <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css" />
    </head>
    <body>
        <div style=" 700px;margin: 0 auto">
            <h1>资产列表</h1>
            <table class="table table-bordered table-striped">
                <thead id="tbHead">
                    <tr>
    {#                    标签中的数据都是通过ajax 的dom 操作动态创建插入的#}
                    </tr>
                </thead>
                <tbody id="tbBody">
                </tbody>
            </table>
        </div>
    
        <script src="/static/jquery-1.12.4.js"></script>
        <script src="/static/nb-list.js"></script>
        <script>
            $.xx('/backend/asset_json.html');       //xx为封装在nb-list.js 中的功能
        </script>
    </body>
    </html>
    View Code

    封装的js 代码nb-list.js

    /**
     * Created by Administrator on 2017/8/2.
     */
    (function (jq) {
    
        var GLOBAL_DICT = {};
        /*
        {
            'device_type_choices': (
                                        (1, '服务器'),
                                        (2, '交换机'),
                                        (3, '防火墙'),
                                    )
            'device_status_choices': (
                                        (1, '上架'),
                                        (2, '在线'),
                                        (3, '离线'),
                                        (4, '下架'),
                                    )
        }
         */
    
        // 为字符串创建format方法,用于字符串格式化
        String.prototype.format = function (args) {
            return this.replace(/\{(\w+)\}/g, function (s, i) {
                return args[i];
            });
        };
    
        function initial(url) {
            $.ajax({
                url: url,
                type: 'GET',  // 获取数据
                dataType: 'JSON',
                success: function (arg) {
                    $.each(arg.global_dict, function (k, v) {
                        GLOBAL_DICT[k] = v                 //为了方便调用把global_dic赋值到全局变量GLOBAL_DICT
                    });
    
                    /*
                     {
                     'server_list':list(server_list), # 所有数据
                     'table_config':table_config      # 所有配置
                      'global_dict':{
                            'device_type_choices': (
                                                        (1, '服务器'),
                                                        (2, '交换机'),
                                                        (3, '防火墙'),
                                                    )
                            'device_status_choices': (
                                                        (1, '上架'),
                                                        (2, '在线'),
                                                        (3, '离线'),
                                                        (4, '下架'),
                                                    )
                        }
                     }
                     */
                    initTableHeader(arg.table_config);
                    initTableBody(arg.server_list, arg.table_config);
                }
            })
        }
    
        function initTableHeader(tableConfig) {
            /*
             [
             {'q':'id','title':'ID'},
             {'q':'hostname','title':'主机名'},
             ]
             */
            $.each(tableConfig, function (k, v) {
                if (v.display) {                //display 为true 时写入标签
                    var tag = document.createElement('th');
                    tag.innerHTML = v.title;
                    $('#tbHead').find('tr').append(tag);
                }
            })
        }
    
        function initTableBody(serverList, tableConfig) {
            /*
             serverList = [
             {'id': 1, 'hostname':c2.com, create_at: xxxx-xx-xx-},
             {'id': 1, 'hostname':c2.com, create_at: xxxx-xx-xx-},
             {'id': 1, 'hostname':c2.com, create_at: xxxx-xx-xx-},
             {'id': 1, 'hostname':c2.com, create_at: xxxx-xx-xx-},
             ]
             */
            $.each(serverList, function (k, row) {
                // row: {'id': 1, 'hostname':c2.com, create_at: xxxx-xx-xx-}
                /*
                 <tr>
                 <td>id</td>
                 <td>hostn</td>
                 <td>create</td>
                 </tr>
                 */
                var tr = document.createElement('tr');
                $.each(tableConfig, function (kk, rrow) {
                    // kk: 1  rrow:{'q':'id','title':'ID'},         // rrow.q = "id"
                    // kk: .  rrow:{'q':'hostname','title':'主机名'},// rrow.q = "hostname"
                    // kk: .  rrow:{'q':'create_at','title':'创建时间'}, // rrow.q = "create_at"
                    if (rrow.display) {
                        var td = document.createElement('td');
                        /*
                         if(rrow['q']){
                         td.innerHTML = row[rrow.q];
                         }else{
                         td.innerHTML = rrow.text;
                         }*/
                        // rrow['q']
                        // rrow['text']
                        // rrow.text.tpl = "asdf{n1}sdf"
                        // rrow.text.kwargs = {'n1':'@id','n2':'@@123'}
                        var newKwargs = {}; // {'n1':'1','n2':'123'}
                        $.each(rrow.text.kwargs, function (kkk, vvv) {
                            var av = vvv;
                            if (vvv.substring(0, 2) == '@@') {
                                var global_dict_key = vvv.substring(2, vvv.length);//得到设备状态device_type_choices或device_status_choices
                                var nid = row[rrow.q];                             //先查出设备状态id或设备类型id
                                console.log(nid, global_dict_key); // 1 "device_type_choices"
                                /*
                                    device_type_choices = (
                                                            (1, '服务器'),
                                                            (2, '交换机'),
                                                            (3, '防火墙'),
                                                            )
                                    device_status_choices = (
                                                            (1, '上架'),
                                                            (2, '在线'),
                                                            (3, '离线'),
                                                            (4, '下架'),
                                                           )
                                */
                                $.each(GLOBAL_DICT[global_dict_key], function (gk, gv) {
                                    if (gv[0] == nid) {
                                        av = gv[1];
                                    }
                                })
                            }
                            else if (vvv[0] == '@') {
                                av = row[vvv.substring(1, vvv.length)];
                            }
                            newKwargs[kkk] = av;
                        });
                        var newText = rrow.text.tpl.format(newKwargs);
                        td.innerHTML = newText;
                        $(tr).append(td);
                    }
                });
                $('#tbBody').append(tr);
    
            })
        }
    
        jq.extend({
            xx: function (url) {
                initial(url);
            }
        })
    })(jQuery);
    View Code
  • 相关阅读:
    OpenJudge计算概论-寻找山顶
    OpenJudge计算概论-配对碱基链
    OpenJudge计算概论-分配病房
    OpenJudge计算概论-计算鞍点
    OpenJudge计算概论-错误探测
    OpenJudge计算概论-文字排版
    OpenJudge计算概论-二维数组右上左下遍历
    OpenJudge-计算点的距离并排序
    OpenJudge计算概论-找最大数序列
    Openjudge计算概论-奇数单增序列
  • 原文地址:https://www.cnblogs.com/fanggege/p/10196277.html
Copyright © 2020-2023  润新知