CMDB项目CURD组件之基于jQuery扩展封装组件

request.body

from django.shortcuts import render,HttpResponse
from django.views import View
import json

class AssetView(View):

    def get(self,request,*args,**kwargs):
        # 数据库中获取数据
        return render(request,‘asset.html‘)

class AssetJsonView(View):
    def get(self,request,*args,**kwargs):
        # 数据库中获取数据
        table_config = [
            {
                ‘q‘: None,
                ‘title‘: "选项",
                ‘display‘: True,
                ‘text‘: {‘content‘: "<input type=‘checkbox‘ />","kwargs": {}},
                ‘attrs‘: {}
            },
            {
                ‘q‘: ‘id‘,
                ‘title‘: ‘ID‘,
                ‘display‘: False,
                ‘text‘:{},
                ‘attrs‘: {}
            },
            {
                ‘q‘: ‘device_type_id‘,
                ‘title‘: ‘资产类型‘,
                ‘display‘: True,
                ‘text‘: {‘content‘: "{n}", ‘kwargs‘: {‘n‘: "@@device_type_choices"}},
                ‘attrs‘: {}
            },
            {
                ‘q‘: ‘device_status_id‘,
                ‘title‘: ‘状态‘,
                ‘display‘: True,
                ‘text‘: {‘content‘: "{n}", ‘kwargs‘: {‘n‘: "@@device_status_choices"}},
                ‘attrs‘: {‘name‘:‘device_status_id‘,‘origin‘:"@device_status_id",‘edit-enable‘: ‘true‘, ‘edit-type‘: ‘select‘,"global-name": ‘device_status_choices‘}
            },
            {
                ‘q‘: ‘idc__id‘,
                ‘title‘: ‘IDC‘,
                ‘display‘: False,
                ‘text‘: {},
                ‘attrs‘: {}
            },
            {
                ‘q‘: ‘idc__name‘,
                ‘title‘: ‘IDC‘,
                ‘display‘: True,
                ‘text‘: {‘content‘: "{n}", ‘kwargs‘: {‘n‘: "@idc__name"}},
                ‘attrs‘: {‘name‘:‘idc_id‘,‘origin‘:"@idc__id",‘edit-enable‘: ‘true‘, ‘edit-type‘: ‘select‘,"global-name": ‘idc_choices‘}
            },
            {
                ‘q‘: ‘cabinet_order‘,
                ‘title‘: ‘机柜位置‘,
                ‘display‘: True,
                ‘text‘: {‘content‘: "{n}",‘kwargs‘: {‘n‘: "@cabinet_order"}},
                ‘attrs‘: {‘name‘:‘cabinet_order‘,‘origin‘:"@cabinet_order",‘edit-enable‘: ‘true‘, ‘edit-type‘: ‘input‘}
            },
            {
                ‘q‘: ‘cabinet_num‘,
                ‘title‘: ‘机柜号‘,
                ‘display‘: True,
                ‘text‘: {‘content‘: "{n}", ‘kwargs‘: {‘n‘: "@cabinet_num"}},
                ‘attrs‘: {},
            },
            {
                ‘q‘: None,
                ‘title‘: ‘操作‘,
                ‘display‘: True,
                ‘text‘: {‘content‘: "<a href=‘/assetdetail-{m}.html‘>{n}</a>", ‘kwargs‘: {‘n‘: ‘查看详细‘,‘m‘: ‘@id‘}},
                ‘attrs‘: {},
            }
        ]

        q_list = []
        for i in table_config:
            if not i[‘q‘]:
                continue
            q_list.append(i[‘q‘])

        from repository import models
        # 分页组件用户获取数据
        data_list = models.Asset.objects.all().values(*q_list)
        data_list = list(data_list)

        result = {
            ‘table_config‘:table_config,
            ‘data_list‘:data_list,
            ‘global_dict‘: {
                ‘device_type_choices‘: models.Asset.device_type_choices,
                ‘device_status_choices‘: models.Asset.device_status_choices,
                ‘idc_choices‘: list(models.IDC.objects.values_list(‘id‘,‘name‘))
            },
            # 分页组件生成页码信息
            ‘pager‘: """<li><a>1</a></li><li><a>2</a></li><li><a>3</a></li><li><a>4</a></li><li><a>5</a></li>"""

        }
        return HttpResponse(json.dumps(result))

    def put(self,request,*args,**kwargs):
        content = request.body
        v = json.loads(str(content,encoding=‘utf-8‘))
        print(v)
        ret = {
            ‘status‘:True
        }
        return HttpResponse(json.dumps(ret))

class BuinessUnitView(View):

    def get(self,request,*args,**kwargs):
        # 数据库中获取数据
        return render(request,‘business_unit.html‘)

class BuinessUnitJsonView(View):
    def get(self,request,*args,**kwargs):
        # 数据库中获取数据
        table_config = [
            {
                ‘q‘: None,
                ‘title‘: "选项",
                ‘display‘: True,
                ‘text‘: {‘content‘: "<input type=‘checkbox‘ />","kwargs": {}},
                ‘attrs‘: {}
            },
            {
                ‘q‘: ‘id‘,
                ‘title‘: ‘ID‘,
                ‘display‘: False,
                ‘text‘:{},
                ‘attrs‘: {}
            },
            {
                ‘q‘: ‘name‘,
                ‘title‘: ‘业务线名称‘,
                ‘display‘: True,
                ‘text‘: {‘content‘: "{n}", ‘kwargs‘: {‘n‘: "@name"}},
                ‘attrs‘: {‘edit-enable‘:‘true‘,‘edit-type‘:‘input‘,‘origin‘: ‘@name‘}
            },
            {
                ‘q‘: ‘contact_id‘,
                ‘title‘: ‘联系人组‘,
                ‘display‘: False,
                ‘text‘: {},
                ‘attrs‘: {}
            },
            {
                ‘q‘: ‘contact__name‘,
                ‘title‘: ‘联系人组‘,
                ‘display‘: True,
                ‘text‘: {‘content‘: "{n}", ‘kwargs‘: {‘n‘: "@contact__name"}},
                ‘attrs‘: {‘edit-enable‘:‘true‘,‘edit-type‘:‘select‘,‘origin‘: ‘@contact_id‘,"global-name": ‘contact_choices‘}
            },
            {
                ‘q‘: ‘manager__name‘,
                ‘title‘: ‘管理员组‘,
                ‘display‘: True,
                ‘text‘: {‘content‘: "{n}", ‘kwargs‘: {‘n‘: "@manager__name"}},
                ‘attrs‘: {}
            },
            {
                ‘q‘: None,
                ‘title‘: ‘操作‘,
                ‘display‘: True,
                ‘text‘: {‘content‘: "<a href=‘/assetdetail-{m}.html‘>{n}</a>", ‘kwargs‘: {‘n‘: ‘查看详细‘,‘m‘: ‘@id‘}},
                ‘attrs‘: {},
            }
        ]

        q_list = []
        for i in table_config:
            if not i[‘q‘]:
                continue
            q_list.append(i[‘q‘])

        from repository import models

        data_list = models.BusinessUnit.objects.all().values(*q_list)
        data_list = list(data_list)

        result = {
            ‘table_config‘:table_config,
            ‘data_list‘:data_list,
            ‘global_dict‘: {
                # ‘device_type_choices‘: models.Asset.device_type_choices,
                # ‘device_status_choices‘: models.Asset.device_status_choices,
                # ‘idc_choices‘: list(models.IDC.objects.values_list(‘id‘,‘name‘))
                ‘contact_choices‘:list(models.UserGroup.objects.values_list(‘id‘,‘name‘))
            },
            ‘pager‘: """<li><a>1</a></li><li><a>2</a></li><li><a>3</a></li><li><a>4</a></li><li><a>5</a></li>"""

        }
        return HttpResponse(json.dumps(result))

    def put(self,request,*args,**kwargs):
        content = request.body
        v = json.loads(str(content,encoding=‘utf-8‘))
        print(v)
        ret = {
            ‘status‘:True
        }
        return HttpResponse(json.dumps(ret))

views

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css" />
    <style>

    </style>
</head>
<body>
{#    <select id="i1">#}
{#        <option>上阿海</option>#}
{#        <option>北京</option>#}
{#        <option>广州</option>#}
{#    </select>#}

    <div style="width: 800px;margin: 0 auto;">
        <h1>资产列表</h1>
        <div class="btn-group" role="group" aria-label="...">
          <button id="idCheckAll" type="button" class="btn btn-default">全选</button>
          <button id="idReverseAll" type="button" class="btn btn-default">反选</button>
          <button id="idCancelAll" type="button" class="btn btn-default">取消</button>
          <button id="idEditMode" type="button" class="btn btn-default">进入编辑模式</button>
          <button type="button" class="btn btn-default">批量删除</button>
          <button id="idSave" type="button" class="btn btn-default">保存</button>
          <a id="idAdd" href="/web/asset-add.html" class="btn btn-default">添加</a>
        </div>
        <table class="table table-bordered">
            <thead id="table_th"></thead>
            <tbody id="table_tb"></tbody>
        </table>
        <ul id="idPagination" class="pagination">

        </ul>
    </div>

    <script src="/static/js/jquery-3.1.1.js"></script>
    <script src="/static/js/nbList.js"></script>

    <script>
        $(function () {
            $.NB("/web/asset-json.html");
        });

    </script>

</body>
</html>

asset.html

(function () {
        var requestUrl = null;
        function bindChangePager() {
            $(‘#idPagination‘).on(‘click‘,‘a‘,function () {
                var num = $(this).text();
                init(num);

            })
        }

        function bindSave() {
            $(‘#idSave‘).click(function () {
                var postList = [];
                //找到已经编辑过的tr,tr has-edit=‘true‘
                $(‘#table_tb‘).find(‘tr[has-edit="true"]‘).each(function () {
                    // $(this) => tr
                    var temp = {};
                    var id = $(this).attr(‘row-id‘);
                    temp[‘id‘] = id;
                    $(this).children(‘[edit-enable="true"]‘).each(function () {
                        // $(this) = > td
                        var name = $(this).attr(‘name‘);
                        var origin = $(this).attr(‘origin‘);
                        var newVal = $(this).attr(‘new-val‘);
                        if (origin != newVal){
                            temp[name] = newVal;
                        }
                    });
                    postList.push(temp);
                })

                $.ajax({
                    url:requestUrl,
                    type: ‘PUT‘,
                    data: {‘post_list‘: JSON.stringify(postList)},
                    dataType: ‘JSON‘,
                    success:function (arg) {
                        if(arg.status){
                            init(1);
                        }else{
                            alert(arg.error);
                        }
                    }
                })
            })
        }

        function bindReverseAll() {
            $(‘#idReverseAll‘).click(function () {
                $(‘#table_tb‘).find(‘:checkbox‘).each(function () {
                    // $(this) => checkbox
                    if($(‘#idEditMode‘).hasClass(‘btn-warning‘)) {
                        if($(this).prop(‘checked‘)){
                            $(this).prop(‘checked‘,false);
                            trOutEditMode($(this).parent().parent());
                        }else{
                            $(this).prop(‘checked‘,true);
                            trIntoEditMode($(this).parent().parent());
                        }
                    }else{
                        if($(this).prop(‘checked‘)){
                            $(this).prop(‘checked‘,false);
                        }else{
                            $(this).prop(‘checked‘,true);
                        }
                    }
                })
            })
        }

        function bindCancelAll() {
            $(‘#idCancelAll‘).click(function () {
                $(‘#table_tb‘).find(‘:checked‘).each(function () {
                    // $(this) => checkbox
                    if($(‘#idEditMode‘).hasClass(‘btn-warning‘)){
                        $(this).prop(‘checked‘,false);
                        // 退出编辑模式
                        trOutEditMode($(this).parent().parent());
                    }else{
                        $(this).prop(‘checked‘,false);
                    }
                });
            })
        }

        function bindCheckAll() {
            $(‘#idCheckAll‘).click(function () {
                $(‘#table_tb‘).find(‘:checkbox‘).each(function () {
                    // $(this)  = checkbox
                    if($(‘#idEditMode‘).hasClass(‘btn-warning‘)){
                        if($(this).prop(‘checked‘)){
                            // 当前行已经进入编辑模式了
                        }else{
                            // 进入编辑模式
                            var $currentTr = $(this).parent().parent();
                            trIntoEditMode($currentTr);
                            $(this).prop(‘checked‘,true);
                        }
                    }else{
                        $(this).prop(‘checked‘,true);
                    }
                })
            })
        }

        function bindEditMode() {
            $(‘#idEditMode‘).click(function () {
                var editing = $(this).hasClass(‘btn-warning‘);
                if(editing){
                    // 退出编辑模式
                    $(this).removeClass(‘btn-warning‘);
                    $(this).text(‘进入编辑模式‘);

                    $(‘#table_tb‘).find(‘:checked‘).each(function () {
                        var $currentTr = $(this).parent().parent();
                        trOutEditMode($currentTr);
                    })

                }else{
                    // 进入编辑模式
                    $(this).addClass(‘btn-warning‘);
                    $(this).text(‘退出编辑模式‘);
                    $(‘#table_tb‘).find(‘:checked‘).each(function () {
                        var $currentTr = $(this).parent().parent();
                        trIntoEditMode($currentTr);
                    })
                }
            })
        }

        function bindCheckbox() {
            // $(‘#table_tb‘).find(‘:checkbox‘).click()
            $(‘#table_tb‘).on(‘click‘,‘:checkbox‘,function () {

                if($(‘#idEditMode‘).hasClass(‘btn-warning‘)){
                    var ck = $(this).prop(‘checked‘);
                    var $currentTr = $(this).parent().parent();
                    if(ck){
                        // 进入编辑模式
                        trIntoEditMode($currentTr);
                    }else{
                        // 退出编辑模式
                        trOutEditMode($currentTr)
                    }
                }
            })
        }

        function trIntoEditMode($tr) {
            $tr.addClass(‘success‘);
            $tr.attr(‘has-edit‘,‘true‘);
            $tr.children().each(function () {
                // $(this) => td
                var editEnable = $(this).attr(‘edit-enable‘);
                var editType = $(this).attr(‘edit-type‘);
                if(editEnable==‘true‘){
                    if(editType == ‘select‘){
                        var globalName = $(this).attr(‘global-name‘); //  "device_status_choices"
                        var origin = $(this).attr(‘origin‘); // 1
                        // 生成select标签
                        var sel = document.createElement(‘select‘);
                        sel.className = "form-control";
                        $.each(window[globalName],function(k1,v1){
                            var op = document.createElement(‘option‘);
                            op.setAttribute(‘value‘,v1[0]);
                            op.innerHTML = v1[1];
                            $(sel).append(op);
                        });
                        $(sel).val(origin);

                        $(this).html(sel);

                        // 下拉框
                        /*
                        *  <select>
                        *      <option value=‘1‘>在线</option>
                        *      <option value=‘2‘>下线</option>
                        *      <option value=‘3‘>离线</option>
                        *  </select>
                        *
                        * */
                        //  在线

                    }else if(editType == ‘input‘){
                        // input文本框
                        // *******可以进入编辑模式*******
                        var innerText = $(this).text();
                        var tag = document.createElement(‘input‘);
                        tag.className = "form-control";
                        tag.value = innerText;
                        $(this).html(tag);
                    }
                }
            })
        }

        function trOutEditMode($tr){
            $tr.removeClass(‘success‘);
            $tr.children().each(function () {
                // $(this) => td
                var editEnable = $(this).attr(‘edit-enable‘);
                var editType = $(this).attr(‘edit-type‘);
                if(editEnable==‘true‘){
                    if (editType == ‘select‘){
                        // 获取正在编辑的select对象
                        var $select = $(this).children().first();
                        // 获取选中的option的value
                        var newId = $select.val();
                        // 获取选中的option的文本内容
                        var newText = $select[0].selectedOptions[0].innerHTML;
                        // 在td中设置文本内容
                        $(this).html(newText);
                        $(this).attr(‘new-val‘,newId);

                    }else if(editType == ‘input‘) {
                        // *******可以退出编辑模式*******
                        var $input = $(this).children().first();
                        var inputValue = $input.val();
                        $(this).html(inputValue);
                        $(this).attr(‘new-val‘,inputValue);
                    }

                }
            })
        }

        String.prototype.format = function (kwargs) {
            // this ="laiying: {age} - {gender}";
            // kwargs =  {‘age‘:18,‘gender‘: ‘女‘}
            var ret = this.replace(/\{(\w+)\}/g,function (km,m) {
                return kwargs[m];
            });
            return ret;
        };

        function init(pager) {
            $.ajax({
                url: requestUrl,
                type: ‘GET‘,
                data: {‘pager‘:pager},
                dataType: ‘JSON‘,
                success:function (result) {
                    initGlobalData(result.global_dict);
                    initHeader(result.table_config);
                    initBody(result.table_config,result.data_list);
                    initPager(result.pager);
                }
            })

        }
        function initPager(pager){
            $(‘#idPagination‘).html(pager);
        }

        function initHeader(table_config) {
            /*
            table_config = [
                {
                    ‘q‘: ‘id‘,
                    ‘title‘: ‘ID‘,
                    ‘display‘:false
                },
                {
                    ‘q‘: ‘name‘,
                    ‘title‘: ‘随便‘,
                    ‘display‘: true
                }
            ]
             */

             /*
            <tr>
                <th>ID</th>
                <th>用户名</th>
            </tr>
            */
            var tr = document.createElement(‘tr‘);
            $.each(table_config,function (k,item) {
                if(item.display){
                    var th = document.createElement(‘th‘);
                    th.innerHTML = item.title;
                    $(tr).append(th);
                }

            });
            $(‘#table_th‘).empty();
            $(‘#table_th‘).append(tr);
        }

        function initBody(table_config,data_list){
            $(‘#table_tb‘).empty();
            for(var i=0;i<data_list.length;i++){
                var row = data_list[i];
                // row = {‘cabinet_num‘: ‘12B‘, ‘cabinet_order‘: ‘1‘, ‘id‘: 1},
                var tr = document.createElement(‘tr‘);
                tr.setAttribute(‘row-id‘,row[‘id‘]);
                $.each(table_config,function (i,colConfig) {
                   if(colConfig.display){
                       var td = document.createElement(‘td‘);
                       /* 生成文本信息 */
                       var kwargs = {};
                       $.each(colConfig.text.kwargs,function (key,value) {

                           if(value.substring(0,2) == ‘@@‘){
                               var globalName = value.substring(2,value.length); // 全局变量的名称
                               var currentId = row[colConfig.q]; // 获取的数据库中存储的数字类型值
                               var t = getTextFromGlobalById(globalName,currentId);
                               kwargs[key] = t;
                           }
                           else if (value[0] == ‘@‘){
                                kwargs[key] = row[value.substring(1,value.length)]; //cabinet_num
                           }else{
                                kwargs[key] = value;
                           }
                       });
                       var temp = colConfig.text.content.format(kwargs);
                       td.innerHTML = temp;

                       /* 属性colConfig.attrs = {‘edit-enable‘: ‘true‘,‘edit-type‘: ‘select‘}  */
                        $.each(colConfig.attrs,function (kk,vv) {
                            if(vv[0] == ‘@‘){
                                td.setAttribute(kk,row[vv.substring(1,vv.length)]);
                            }else{
                                td.setAttribute(kk,vv);
                            }
                        });

                       $(tr).append(td);
                   }
                });

                $(‘#table_tb‘).append(tr);
            }
        }

        function initGlobalData(global_dict) {
            $.each(global_dict,function (k,v) {
                // k = "device_type_choices"
                // v= [[0,‘xx‘],[1,‘xxx‘]]
                // device_type_choices = 123;
                window[k] = v;
            })
        }

        function getTextFromGlobalById(globalName,currentId) {
            // globalName = "device_type_choices"
            // currentId = 1
            var ret = null;
            $.each(window[globalName],function (k,item) {
                if(item[0] == currentId){
                    ret = item[1];
                    return
                }
            });
            return ret;
        }

        jQuery.extend({
            ‘NB‘: function (url) {
                requestUrl = url;
                init();
                bindEditMode();
                bindCheckbox();
                bindCheckAll();
                bindCancelAll();
                bindReverseAll();
                bindSave();
                bindChangePager();
            },
            ‘changePager‘: function (num) {
                init(num);
            }
        })
})();

nbLIst.js

原文地址:https://www.cnblogs.com/jintian/p/11300521.html

时间: 2024-10-30 06:59:19

CMDB项目CURD组件之基于jQuery扩展封装组件的相关文章

基于jQuery的TreeGrid组件详解

一.TreeGrid组件相关的类 1.TreeGrid(_config) _config:json格式的数据,组件所需要的数据都通过该参数提供. 2.TreeGridItem(_root, _rowId, _rowIndex, _rowData) _root:显示组件实例的目标容器对象. _rowId:选中行的id. _rowIndex:选中行的索引. _rowData:json格式的行数据. 二._config参数详解 id:组件实例的id. width:组件实例的宽度. renderTo:用

vue组件篇(2)---封装组件并发布到npm

瞎说说 vue小白,要进行应用开发:你们都用什么UI框架,求指教,不想踩坑(想太多,不踩坑???不存在的!!!too young too simple-) 同学1:pc端我用element UI,感觉组件的API方法.属性比较完善...?? 同学2:哈?我个人感觉他的样式有些生硬,不够炫酷美观??,用iView吧,组件丰富,动画效果cool~~~?? 同学3:真的吗?阔是有人说,iView组件虽然完美的把其他UI组件有的缺点完美避过,但是某某组件不够人性化....?? 同学4:用vue-beau

CMDB项目CURD组件进入编辑模式

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css" /> <style

CMDB项目CURD组件之全选取消反选和编辑模式

$(':checked') 选中的所有元素 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css

CMDB项目CURD组件之自定义td属性

from django.shortcuts import render,HttpResponse from django.views import View import json class AssetView(View): def get(self,request,*args,**kwargs): # 数据库中获取数据 return render(request,'asset.html') class AssetJsonView(View): def get(self,request,*ar

CMDB项目CURD组件之分页功能

原文地址:https://www.cnblogs.com/jintian/p/11300546.html

CMDB项目CURD组件之搜索功能介绍

#!/usr/bin/env python # -*- coding:utf-8 -*- import json from django.db.models import Q from repository import models from utils.pager import PageInfo from utils.response import BaseResponse from django.http.request import QueryDict from .base import

基于jQuery的TreeGrid组件

/** * @author 陈举民 * @version 1.0 * @link http://chenjumin.iteye.com/blog/419522 */ TreeGrid = function (_config) { _config = _config || {}; var s = ""; var rownum = 0; var __root; var __selectedData = null; var __selectedId = null; var __selecte

基于jquery扩展漂亮的下拉框——ComboBox

关于web前端自定义控件——ComboBox(下拉框),以往我在使用下拉框控件老是为了样式丑陋而烦恼,现在分享这个控件,希望有用的同仁们可以收藏,或进行二次修改,达到你想要的效果. 分解自定义下拉框: 1.创建构造函数,初始化赋值控件值. 2.绑定控件呈现在前台. 3.点击下拉框控件,展示下拉列表 4.点击触发下拉框控件,收起下拉列表. 5.点击下拉项触发事件. 代码如下: Html代码: 1 <b class="select_type"></b> css样式: