zoukankan      html  css  js  c++  java
  • 前台kendo ui js grid框架增删改查

    附:api 地址:http://docs.telerik.com/kendo-ui/api/introduction

    组件示例代码地址:http://demos.telerik.com/kendo-ui/

    1,首先定义好后台数据,返回一组json数据

    @RequestMapping("/showUsers.do")
    	@ResponseBody
    	public Map<String, Object> userList(
    			@RequestParam(value = "page", required = false, defaultValue = "0") Integer page,
    			@RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize) {
    		List<UserDto> users=userService.list(page,pageSize);
    		int count=userService.getTotalCount();
    		Map<String, Object> _result = new HashMap<String, Object>();
    		_result.put("results", users);
    		_result.put("__count", count);
    		
    		Map<String, Object> result = new HashMap<String, Object>();
    		result.put("d", _result);
    		return result;
    	}
    	
    	
    	@RequestMapping("/users.do")
    	public String  userListPage() {
    		return "user/user.jsp";
    	}
    

     如上:后台json格式为固定,__count 对应数据总条数,前台会根据配置自动分页,

    当然返回json格式也可以自定义,如返回格式为

    String json = new Gson().toJson(list);
    return "{"users" :" + json + ", "totalSize" :" + totalSize + "}";
    

     如此前台定义 schema 时,需加入如下配置:(具体配置下面会看到)
                    data : "hosts",
                    total: "totalSize",

    2,下面来看一下前台部分

    a,首先要有一个jsp页面,并定义一个有id的div

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>  
    <%@ taglib prefix='spring' uri="http://www.springframework.org/tags" %>
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
    
    <head>
    <link rel="stylesheet" type="text/css" href="<spring:url value='/resources/css/common.css'/>" />
    <link rel="stylesheet" type="text/css" href="<spring:url value='/resources/js/plugins/easyUI/themes/default/easyui.css' />">
    <link rel="stylesheet" type="text/css" href="<spring:url value='/resources/css/themes/default/main.css' />">
    <link rel="stylesheet" type="text/css" href="<spring:url value='/resources/css/themes/default/icon.css' />">
    <link rel="stylesheet" type="text/css" href="<spring:url value='/resources/css/themes/default/bootstrap.css' />">
    <link rel="stylesheet" type="text/css" href='<spring:url value="/resources/js/plugins/kendoui/styles/kendo.common.min.css"/>'/>
    <link rel="stylesheet" type="text/css" href='<spring:url value="/resources/js/plugins/kendoui/styles/kendo.uniform.min.css"/>'/>
    <link rel="stylesheet" type="text/css" href='<spring:url value="/resources/js/plugins/kendoui/styles/kendo.silver.min.css"/>'/>
    <link rel="stylesheet" type="text/css" href='<spring:url value="/resources/css/kendo_ui_gray.css"/>'/>
    
    <script src="<spring:url value='/resources/js/plugins/kendoui/js/jquery.min.js' />"></script>
    <script src='<spring:url value="/resources/js/plugins/kendoui/js/kendo.all.min.js"/>'></script>
    <script src="<spring:url value='/resources/js/plugins/jquery.easyui.min.js' />"></script>
    <script src="<spring:url value='/resources/js/modules/user/userList.js' />"></script>
    </head>
    <body>
    <div id="example" class="k-content">
            <div id="clientsDb">
                <div id="grid" style="height: 380px"></div>
            </div>
    </div>
    <div id="dialog"></div>
    </body>

    b,来看一下js部分, 首先需要定义一个datasource

    $(function() {
        var dateFormate = "yyyy-MM-dd HH:mm:ss";
        
        var prefix = "user";
        
        var dataSource = new kendo.data.DataSource({
            type: "odata",
            pageSize : 20,
            serverPaging: true,//服务器端是否进行分页查询
           serverFiltering: true,
            transport : {
                read : {
                    url : prefix + '/showUsers.do',
                    dataType : "json",
                },
                update: {
                    url: prefix + '/save.do',
                    dataType: "json",
                    contentType:"application/x-www-form-urlencoded",
                    type : "post",
                    data: function() {
                        var roleid=$("#roleId").val();
                        return {
                         roleId:roleid
                        }
                      }
                },
                destroy: {
                  url: prefix + '/delete.do',
                  contentType:"application/x-www-form-urlencoded",
                    type : "post",
                  dataType: "json",
                },
                create: {
                    url: prefix + '/save.do',
                    dataType: "json",
                    contentType:"application/x-www-form-urlencoded",
                    type : "post",
                    data: function() {
                        var roleid=$("#roleId").val();
                        return {
                         roleId:roleid
                        }
                      }
                },
                parameterMap: function(data, type) {
                    if (type == "create"||type == "update") {
                        delete data.role;
                        
                        var roleid=$("#roleId").val();
                        data.roleId=roleid;
                    }
                    return data;
                }
            },
            requestEnd: function(e) {
                var response = e.response;
                if(response){
                    var type = e.type;
                    if(type !='read'){
                        var status = response.status;
                        if(status == 200){
                            //lert(response.message);
                            this.read();
                        } else {
                            alert(response.message);
                        }
                    }
                }else{
                    alert("服务器异常,请重试!");
                }
                
            },
            schema : {
                model : {
                    id : "id",
                    fields : {
                        id : {type : "string"},
                        password :{type : "string"},
                        realName : {type : "string"},
                        phone : {type : "string"},
                        status : {
                            type : "string",
                            defaultValue : "激活"
                        },
                        userName : {type : "string"},
                        email : {type : "string"},
                        role : {},
                        createdTime : {
                            type : "string",
                            //this field will not be editable (default value is true)
                            editable: false,
                            defaultValue: kendo.toString(new Date(), dateFormate)
                        }
                    }
                }
            },
            sort : {
                field : "createdTime",
                dir : "desc"
            },

        });
     
    });

    下面说一下重要的配置点,

    dataSource:定义grid加载的数据源,以及配置增删改 表单提交的url和需要的表单参数

    首先需要配置一个dataSource来获取后台数据,以及增删改的操作
    那个type:odata 官网是这么说的If set the data source will use a predefined transport and/or schema.
    The supported values are "odata" which supports the OData v.2 protocol and "signalr".

    没看懂,反正就默认的odata就对了
    transport ,就是配置增删改查的连接,配置好,后都会自动操作的
    注意的是sava 与update contentType:"application/x-www-form-urlencoded", 后台可以直接通过对应的bean接收参数,
    (字段类型最好一致,如时间的格式,不然可能会报400的错,其实就是格式没对应,如果出现,可通过firebug查看一下请求的参数书否对应)
    create 中的data可在请求之前进行追加参数,注意是追加,格式也是json格式

    parameterMap
    type 就是“read” “create”等
    data 就是 model
    中定义的属性,是json的格式,可通过判断在提交表单时追加参数,或者去除无关的参数

    requestEnd 是在操作完之后进行的回调时间,可获取到response 进行判断操作是否成功
    对应的有requestStart 可以在请求发送之前进行js操作

    schema  用于在转换后台发送来的数据 对应javabean

    C,下面通过jquery选取 html中定义的对应id的div元素来加载通过kendo实例的grid

      $("#grid").kendoGrid({
                dataSource : dataSource,
                sortable : false,
                selectable : "multiple",// 多选
                height : 500,
                navigatable: true,
                //toolbar: ["create", "save", "cancel"],
                 editable: true,
                toolbar : [ 
                    {
                        name : "create",
                        text : "新增用户"
                    }
                ],
                pageable : {
                    pageSize : 20,// 一页显示多少行数据
                    previousNext : true,// 是否允许有上一页、下一页、首页、尾页摁扭
                    numeric : true,// 是否显示翻页处的页数按钮
                    buttonCount : 5,// 限制页数按钮的显示个数
                    input : false,// 是否显示输入页数的文本框
                    refresh : true,// 是否允许刷新页面
                    pageSizes : true,// 是否允许调整一页显示的行数,可设置[5, 10, 15]
                    messages : {
                        display : "显示  {0}-{1} 条数据 总共 {2} 条数据",
                        empty : "没有数据",
                        itemsPerPage : "选择显示行数",
                        refresh : "刷新",
                        previous : "上一页",
                        next : "下一页",
                        last : "尾页",
                        first : "首页"
                    }
                },
                columns : [ // 显示列定义
                    {
                        field : "realName",
                        width : 100,
                        title : "姓名"
                    }, {
                        field : "userName",
                        width : 120,
                        title : "用户名",
                        attributes : {
                            "class" : "table-cell",
                            style : "text-align: left; font-size: 14px"
                        }
                    }, {
                        field : "password",
                        title : "密码",
                        hidden: true,
                        editor: function (container, options) {
                            $('<input data-text-field="' + options.field + '" ' +
                                    'class="k-input k-textbox" ' +
                                    'type="password" ' +
                                    'data-value-field="' + options.field + '" ' +
                                    'data-bind="value:' + options.field + '"/>')
                                    .appendTo(container);
                        }
                    }, {
                        field : "phone",
                        width : 120,
                        title : "联系电话"
                    }, {
                        field : "email",
                        width : 120,
                        title : "Email"
                    }, {
                        field : "role",
                        width : 80,
                        title : "角色",
                        template: "#=role.name#",
                        editor: roleDropDownEditor
                    },{
                        field : "status",
                        width : 80,
                        title : "启动状态",
                        editor : userStatusDownEditor,
                        template : "#=status#"
                    }, {
                        field : "createdTime",
                        width : 150,
                        title : "创建时间",
                        format : "{0: yyyy-MM-dd HH:mm:ss}"
                    },{
                        command : [ 
                            {
                                name : "edit",
                                text : {
                                    edit : "信息修改",
                                    cancel : "关闭",
                                    update : "提交"
                                }
                            }, {
                                name : "destroy",
                                text : "删除"
                            } 
                        ],
                        title : "操作",
                        width : "160px"
                    } ],
                    editable : {// 设置可以在列表中进行编辑数据
                        // 设置删除时显示的确认信息
                        confirmation : "您确定要进行删除操作吗?",
                        //createAt : "top",// 添加位置,默认是top:从第一行进行添加
                        destroy : true,// 不允许删除
                        mode : "popup",// 设置编辑形式为弹出框(popup)还是在列表中(inline)
    //                    template: kendo.template($("#editTemplate").html())//设置弹出框中加载的内容,设置此项mode必须是popup
                    },
                    /*groupable : {// 设置列表表头
                        messages : {empty : "用户信息列表"}
                    },*/
                    groupable : false                
            });
        
        
        function userStatusDownEditor(container, options){
            var status = options.model.status;
            var data = [
                        { text: "激活", value: "激活" },
                        { text: "冻结", value: "冻结" }
                    ];
            
            var statusDroplist = $('<input required data-text-field="text" data-value-field="value" data-bind="value:' + options.field + '"/>')
            .appendTo(container).kendoDropDownList({
                dataTextField: "text",
                dataValueField: "value",
                dataSource : data
            });
            statusDroplist.data("kendoDropDownList").select(function(dataItem) {
                return dataItem.text === status;
            });
        }
        
        function roleDropDownEditor(container, options) {
            var role = options.model.role;
            //console.log(options);
            var roleDroplist = $('<input required id="roleId" data-text-field="name" data-value-field="id" data-bind="value:' + options.field + '"/>')
                .appendTo(container).kendoDropDownList({
                    valuePrimitive: true,
                    dataTextField:"role.name",
                    dataValueField: "role.id",
                    dataSource: {
                        transport: {
                            read: {
                                url : 'role/getRoles.do',
                                dataType: "json"
                            }
                        }
                    }
                });
           // console.log(roleDroplist.data("kendoDropDownList"));
           /* roleDroplist.data("kendoDropDownList").select(function(dataItem) {
                if(role)
                    return dataItem.value === role.id;
            });*/
        }
    
    

     重要配置参数:

    toolbar 有3个选项 "create", "save", "cancel"  用于save操作,定义后,kendo会通过datasource中的配置自动生成一个form的window
    pageable 用于定义分页的信息,其中后台可直接获取 page,pageSize 参数
    columns 定义显示的javabean中的属性,field 对应javabean属性,title 显示grid的中的head,attributes 可定义一些css

    template 可用于定义 每一条数据中的特定数据内容如:user,对应的role,很明显显示对应的role.name ,就可配置为"#=role.name#",
    也可定义为一个function,返回对应的显示值 如status

    var statusMap= {"A": "Active", "B": "INActive", "C": "Deleted"};
    
    
    
    
      {
                        field: "status",
                        title: "状态",
                template: function(dataItem) { return statusMap[dataItem.status]; },
                        editor: statusDropDownListEditor,
                        80
                    },

    
    
    editor ,用于在update和save的form 中定义编辑组件,如下拉框,他需要定义一个function
    function osDropDownListEditor(container, options){  
                 $('<input required data-text-field="text" data-value-field="value" data-bind="value:' + options.field + '"/>')
                .appendTo(container).kendoDropDownList({
                    dataSource:[{"text": "Active", value:"A"}, {text: "INActive", value:"B"},{text:"Unknown", value:""}],
                    dataTextField: "text",
                    dataValueField: "value",
                });
            };
    
    

    这个事简单的字段取出值对应显示值,不需去数据库,

    下面可看一下user新增时,选择对应的role,首先需要重数据库中取出所有可用的role以供选择

    colums中对应model的定义

     {
                        field : "role",
                        width : 80,
                        title : "角色",
                        template: "#=role.name#",
                        editor: roleDropDownEditor
                    },
    roleDropDownEditor  function
    function roleDropDownEditor(container, options) {
            var role = options.model.role;
            //console.log(options);
            var roleDroplist = $('<input required id="roleId" data-text-field="name" data-value-field="id" data-bind="value:' + options.field + '"/>')
                .appendTo(container).kendoDropDownList({
                    valuePrimitive: true,
                    dataTextField:"name",
                    dataValueField: "id",
                    dataSource: {
                        transport: {
                            read: {
                                url : 'role/getRoles.do',
                                dataType: "json"
                            }
                        }
                    }
                });
           // console.log(roleDroplist.data("kendoDropDownList"));
           /* roleDroplist.data("kendoDropDownList").select(function(dataItem) {
                if(role)
                    return dataItem.value === role.id;
            });*/
        }

    利用kendo的kendoDropDownList

    input中的data-text-field  data-value-field 分别对应下拉框的显示值 与选择是存的value, 填写对应role的id name

    kendoDropDownList的属性

    dataSource:定义要从后台取得role的list
    dataTextField:
    "name", dataValueField: "id",分别对应去到的role中的id,与name,kendo会自动装填到下拉框中
    这里有些问题,kendo在提交表单时好像不能像普通的form表单一样直接通过如定义name=role.id,然后在后台直接通过user.role.来取,
    我也尝试过将role改为json的格式提交,但都失败了,因此值得在save提交时去掉role参数,换成追加参数roleId来实现,这里要说一下表单提交时如果参数对不上可能会出现400的错误,
    这是需要通过firebug查看一下请求时post的参数,
    当然我在后台接收时是通过JavaBean接收的,如果通过map来接收,或者直接通过request.getparameter,应该不会出现。
    command ,用于定义表格中对应每一行的编辑或者删除按钮
    只需把name给与“editor”,“destory” 剩余的就交给kendo吧
  • 相关阅读:
    8088汇编跳转和PSW状态字寄存器
    Delphi的函数指针
    服务器系统及软件常见漏洞
    TGraphiControl响应WM_MOUSEMOVE的过程(以TPaintBox为例)good
    两个奇怪的取地址符号
    把x指针指向的4个字节次序颠倒过来
    DELPHI中的消息处理机制(三种消息处理方法的比较,如何截断消息)
    探索C++的底层机制
    setprecision、fixed、showpoint的用法总结(经典!!超经典!!)
    段寄存器和8种地址寻址方式
  • 原文地址:https://www.cnblogs.com/china2k/p/3789005.html
Copyright © 2011-2022 走看看