首页 > 代码库 > DataGrid--多记录CRUD

DataGrid--多记录CRUD

最近在做一个datagrid,但因为引用的Jquery,加上初学者,所以难免费尽周折。现在将完整版贴出来,跟大家分享,一起切磋,也方便自己回顾学习。

ps:第一次发帖,不知排版效果如何,瑕疵勿怪。

首先是Optdatagrid.html

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>表格operateDataGrid表格</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    
    
    <link rel="stylesheet" href="http://www.mamicode.com/easyui.css" type="text/css"></link>
    <link rel="stylesheet" href="http://www.mamicode.com/icon.css" type="text/css"></link>
    
    <script type="text/javascript" src="http://www.mamicode.com/jquery.min.js"></script>
    <script type="text/javascript" src="http://www.mamicode.com/jquery.easyui.min.js"></script>
    <!-- 引入中文资源? -->
    <script type="text/javascript" src="http://www.mamicode.com/easyui-lang-zh_CN.js"></script>
    <script type="text/javascript" src="http://www.mamicode.com/optDataGrid.js"></script>
    
    <script type="text/javascript">
        //设置datagrid自适应?
        $(window).resize(function () {
            $(‘#dataGrid‘).datagrid(‘resize‘)
        });
    </script>
  </head>
 
  <body>
  <h3>测试增、删、改所用表格</h3>
      <div width="100%">
      <div>
      <a href="http://www.mamicode.com/#" id="01" class="easyui-linkbutton" plain="true" onclick="doSearch()">查询</a>
      </div>
        <table id="dataGrid"></table>
    </div>
    <script>
    function doSearch(){
                        var mydata;
                       var str =" select * from Userinfo;";
                       
                 $("#01").click(function(){
                 $.ajax({
                        url: "http://127.0.0.1:9999/zhangdaicong/crud",
                        type: "post",
                        data:{sql:str},
                        async: false,
                        dataType: "json",
                        success: function (result) {
                        console.info(result);
                        mydata=http://www.mamicode.com/result;

                        }
                        
                        });



    
        $(‘#dataGrid‘).datagrid(‘loadData‘,mydata);
    });
    }
        
        
    </script>
  </body>
</html>

 

接下来是OptDataGrid.js

 

var dataGridOper;
//定义右键点击时选择的行
var rightIndex = -1;

$.extend($.fn.datagrid.methods, {
    //增加时有编辑框
    //第一个参数组件本身,第二个参数要传递的参数
    addEditor: function(jq, param){
        if (param instanceof Array) {
            $.each(param, function(index, item){
                var e = $(jq).datagrid(‘getColumnOption‘, item.field);
                e.editor = item.editor;
            });
        }
        else {
            var e = $(jq).datagrid(‘getColumnOption‘, param.field)
            e.editor = param.editor;
        }
    },
    //修改时没编辑框
    //编辑时使用可以跳过指定的列编辑,对某些列不需要编辑
    // 如 datagrid(‘removeEditor‘,‘password‘),不让编辑密码
    removeEditor: function(jq, param){
        if (param instanceof Array) {
            $.each(param, function(index, item){
                var e = $(jq).datagrid(‘getColumnOption‘, item);
                e.editor = {};
            });
        }
        else {
            var e = $(jq).datagrid(‘getColumnOption‘, param)
            e.editor = {};
        }
    }
})

/**
 * 扩展datagrid的列editor
 * @param {Object} container
 * @param {Object} options
 */
$.extend($.fn.datagrid.defaults.editors, {
    //扩展datatimebox
    datetimebox: {
        init: function(container, options){
            //初始化datatimebox
            var input = $(‘<input />‘).appendTo(container);
            //不可输入
            options.editable = false;
            input.datetimebox(options);
            return input;
        },
        getValue: function(target){
            return $(target).datatimebox(‘getValue‘);
        },
        setValue: function(target, value){
            $(target).datatimebox(‘setValue‘, value);
        },
        resize: function(target, width){
            $(target).datatimebox(‘resize‘, width);
        },
        destroy: function(target){
            //销毁datetimebox弹出的panel
            $(target).datatimebox(‘destroy‘);
        }
    },
    //单选框
    radioButton: {
        init: function(container, options){
            //初始化datatimebox
            var input = $(‘<input type="radio" name="radio" value="http://www.mamicode.com/M" />男 &nbsp;<input type="radio" name="radio" value="http://www.mamicode.com/F" />女&nbsp;‘).appendTo(container);
            return input;
        },
        getValue: function(target){
            alert($(target).val())
            return $(target).val();
        },
        setValue: function(target, value){
            $(target).val(value);
        },
        resize: function(target, width){
        }
    }
});
/*
//js获取项目根路径,如: http://localhost:8088/jquery
function getRootPath(){
    //获取当前网址,如: http://localhost:8088/jquery/easyui/login.jsp
    var curWwwPath = window.document.location.href;
    //获取主机地址之后的目录,如: jquery/easyui/login.jsp
    var pathName = window.document.location.pathname;
    var pos = curWwwPath.indexOf(pathName);
    //获取主机地址,如: http://localhost:8088
    var localhostPaht = curWwwPath.substring(0, pos);
    //获取带"/"的项目名,如:/jquery
    var projectName = pathName.substring(0, pathName.substr(1).indexOf(‘/‘) + 1);
    return (localhostPaht + projectName);
}*/

$(function(){
    operateDataGrid();
});


var operateDataGrid = function(){

    //用于存放操作记录
    var operator = "";
    //存放编辑的行号
    var editorRow = -1;
    dataGridOper = $(‘#dataGrid‘).datagrid({
        
      //  url: "http://127.0.0.1:9999/zhangdaicong/crud",
      //  method: ‘post‘,
        title: ‘用户信息表‘,
        fitColumns: true,
        width: ‘100%‘,
        height: 335,
        loadMsg: ‘loading‘,
        striped: true,
        //idField: ‘oid‘,
        rownumbers: true,
        //设置默认排序字段
        sortName: ‘username‘,
        columns: [[{
            field: ‘oid‘,
            title: ‘编号‘,
            width: 100,
            align: ‘center‘,
            //设置可以排序,则不显示此列
            checkbox: true
        }, {
            field: ‘username‘,
            title: ‘姓名‘,
            width: 100,
            align: ‘center‘,
            //设置可以排序
            sortable: true,
            editor: {
                //string,object string 时指编辑类型,当 object 是options:对象,编辑类型对应的编辑器选项
                type: ‘validatebox‘,
                options: {
                    required: true
                }
            }
        }, {
            field: ‘gender‘,
            title: ‘性别‘,
            width: 100,
            align: ‘center‘,
            sortable: true,
            editor: {
                //string,object
                type: ‘validatebox‘
            
            },
            formatter: function(value, rowData, rowIndex){
                return (($.trim(value) == "F") ? "woman" : "man");
            }
        }, {
            field: ‘phone‘,
            title: ‘联系电话‘,
            width: 100,
            align: ‘center‘,
            sortable: true,
            editor: {
                //string,object
                //type: ‘datetimebox‘,
                type: ‘text‘,
                options: {
                    required: true
                }
            }
        }]],
        pagination: true,
        //工具栏,每个都是一个LinkButton
        toolbar: [{
            id: ‘idAdd‘,
            text: ‘添加 ‘,
            iconCls: ‘icon-add‘,
            plain: ‘true‘,
            //按钮事件
            handler: function(){
                //控制一次只能添加一行
                //if (editorRow == -1) {
                    //增加时可以对用户名进行编辑
                    dataGridOper.datagrid(‘addEditor‘, {
                        field: ‘username‘,
                        editor: {
                            //string,object string 时指编辑类型,当 object 是options:对象,编辑类型对应的编辑器选项
                            type: ‘validatebox‘,
                            options: {
                                required: true
                            }
                        }
                    });
                    
                    
                    
                    operator = "insertData";
                    //在第一行增加
                    dataGridOper.datagrid(‘insertRow‘, {
                        //index:插入进去的行的索引,如果没有定义,就追加此新行,row:行的数据
                        index: 0,
                        row: {
                            //初始化的数据
                            username: ‘请输入姓名‘,
                            gender: ‘输入性别‘,
                            phone: ‘输入电话‘
                        }
                    });
                    //队列进行编辑时必须在columns中列设置editor属性
                    //开始第一行进行编辑,参数index 索引
                    dataGridOper.datagrid(‘beginEdit‘, 0);
                    editorRow = 0;
              /*
              此处是补充功能:获取修改的行,将其保存到数组中然后传给后台。
              
                    var row = $(‘#dataGridOper‘).datagrid("selectRow",0).datagrid("getSelected");
                            
                             console.info(row);*/
                // }
                // else {
                     // $.messager.alert(‘提示‘, ‘请先保存正在修改的数据‘, ‘warning‘);
                  // dataGridOper.datagrid(‘endEdit‘, editorRow);
                 // }
                
            }
        }, ‘-‘, {
            id: ‘idDelete‘,
            text: ‘删除‘,
            disabled: true,
            iconCls: ‘icon-remove‘,
            //按钮事件
            handler: function(){
                //获取选中的行数
                var rows = dataGridOper.datagrid(‘getSelections‘);
                if (rows.length > 0) {
                    //存放选中行的id
                    var ids = [];
                    
                    for (var i = 0; i < rows.length; i++) {
                        ids.push("oid="+rows[i].oid);
                    }
                    //var deletedata=http://www.mamicode.com/{};
                    //deletedata["myarr"] =ids;
                    var str = JSON.stringify(ids);
              
                    var str1 = "{‘list‘:"+str+"}";
                    console.info(str1);
                    //调用后台删除
                    $.ajax({
                        url:"http://127.0.0.1:9999/zhangdaicong/crud/delete",
                        type: "post",
                        data: {deletedata:str1},
                        async: false,
                        dataType:"json",
                        success:function(msg){
                            console.info(msg);
                            //alert(msg);
                            if (msg ==‘{a=6}‘) {
                                //title, msg, icon, fn
                                $.messager.alert(‘系统提示‘, ‘删除数据成功!‘, ‘info‘, function(btn){
                                    //回调函数
                                    dataGridOper.datagrid(‘load‘);
                                });
                            }
                            else
                                if (msg == ‘noData‘) {
                                    $.messager.alert(‘系统提示‘, ‘请选择要删除的数据 ‘, ‘warning‘)
                                }
                                else {
                                    $.messager.alert(‘系统提示‘, ‘删除成功:001‘, ‘error‘)
                                }
                        },
                        error: function(XMLHttpRequest, textStatus, errorThrown){
                            $.messager.alert(‘系统提示‘, ‘删除失败,错误代码:003‘ + textStatus, ‘info‘)
                        }
                    })
                }
                else {
                    //title, msg, icon, fn
                    $.messager.alert(‘系统提示‘, ‘请选择要保存的数据 ‘, ‘info‘);
                }
                
            }
        }, ‘-‘, {
            id: ‘idEdit‘,
            text: ‘修改‘,
            iconCls: ‘icon-edit‘,
            disabled: true,
            handler: function(){
                //控制一次只能编辑一行
                var rows2 = dataGridOper.datagrid(‘getSelections‘);
                
                //console.info(rows2[0]);
                //一次只能编辑一行
                if (rows2.length == 1) {
                    //判断是否有其他行正在编辑
                    if (editorRow == -1) {
                        //不让编辑用户名
                        //dataGridOper.datagrid(‘removeEditor‘, [‘username‘,‘‘]); 传多个对象
                        dataGridOper.datagrid(‘removeEditor‘, ‘username‘);
                        
                        //返回指定行的索引,row 参数可以是一个行记录或者一个 id 字段的值
                        var index1 = dataGridOper.datagrid(‘getRowIndex‘, rows2[0]);
                        operator = "updateData";
                        //在第一行增加
                        //队列进行编辑时必须在columns中列设置editor属性
                        //开始对一行进行编辑,参数index 索引
                        dataGridOper.datagrid(‘beginEdit‘, index1);
                        
                        editorRow = index1;
                    }
                    else {
                        $.messager.confirm(‘提示‘, ‘是否保存正在修改的数据? ‘, function(btn2){
                            //点击确定则保存,否则取消
                            if (btn2) {
                                dataGridOper.datagrid(‘endEdit‘, editorRow);
                                //设置当前无正在编辑的行
                                editorRow = -1;
                            }
                        });
                    }
                }
                else {
                    $.messager.alert(‘提示‘, ‘每次只能对一行进行编辑‘, ‘warning‘);
                }
            }
        }, ‘-‘, {
            id: ‘idSave‘,
            text: ‘保存‘,
            iconCls: ‘icon-save‘,
            //disabled: true,
            handler: function(){
                //结束对第一行进行编辑,参数index 索引
                if (editorRow != -1) {
                    dataGridOper.datagrid(‘endEdit‘, editorRow);
                }
            }
        }, ‘-‘, {
            id: ‘idCancle‘,
            text: ‘放弃编辑‘,
            iconCls: ‘icon-undo‘,
            //disabled: true,
            handler: function(){
                //获取总数
                var paper = dataGridOper.datagrid(‘getPager‘);
                var total = paper.pagination(‘options‘).total;
                //回滚自从创建以来或最后一次调用acceptChanges以来所有更改的数据
                dataGridOper.datagrid(‘rejectChanges‘);
                //重新设置总数
                paper.pagination({total:total});
                editorRow = -1;
                //取消选中时,则删除,修改按钮不可用
                $(‘#idDelete‘).linkbutton(‘disable‘);
                $(‘#idEdit‘).linkbutton(‘disable‘);
            }
        }, ‘-‘],
        onSelect: function(rowIndex, rowData){
            //选中时,则删除,修改按钮可用
            $(‘#idDelete‘).linkbutton(‘enable‘);
            $(‘#idEdit‘).linkbutton(‘enable‘);
        },
        onSelectAll: function(rows){
            //选中时,则删除,修改按钮可用
            $(‘#idDelete‘).linkbutton(‘enable‘);
            $(‘#idEdit‘).linkbutton(‘enable‘);
        },
        onUnselect: function(rowIndex, rowData){
            //当取消全部选中时则按钮不可用
            var rows = dataGridOper.datagrid(‘getSelections‘);
            if (rows.length == 0) {
                //取消选中时,则删除,修改按钮不可用
                $(‘#idDelete‘).linkbutton(‘disable‘);
                $(‘#idEdit‘).linkbutton(‘disable‘);
            }
        },
        onUnselectAll: function(rows){
            //取消选中时,则删除,修改按钮不可用
            $(‘#idDelete‘).linkbutton(‘disable‘);
            $(‘#idEdit‘).linkbutton(‘disable‘);
        },
        onAfterEdit: function(rowIndex, rowData, changes){
            //获取最后一次提交以来更改的行,type 参数表示更改的行的类型,可能的值是:inserted、deleted、updated,等等。
           //dataGridOper.datagrid(‘getChanges‘, ‘inserted‘);//用于判断是增删改的操作
            //当用户完成编辑一行时触发,参数包括rowIndex:编辑行的索引,从 0 开始
            //rowData:编辑行对应的记录 changes:更改的字段/值对
            var urlDatahttp://www.mamicode.com/= "";
            if (operator == "insertData") {
                urlData = http://www.mamicode.com/‘"‘+ rowData.username + ‘" , "‘ + rowData.gender + ‘" , "‘ + rowData.phone+‘"‘;
                
                console.info(urlData);
                $.ajax({
                type: "POST",
                url:  "http://127.0.0.1:9999/zhangdaicong/crud/save",
                data:{savedata:urlData},
                dataType: ‘text‘,
                success: function(msgResult){
                    console.info(msgResult);
                    if (msgResult == "success1") {
                        //提交自从被加载以来或最后一次调用acceptChanges以来所有更改的数据,
                        //保持该数据的状态,否则点击取消编辑,将会回到修改前的数据,相当于提交事务
                        dataGridOper.datagrid(‘acceptChanges‘);
                        //title, msg, icon, fn
                        $.messager.alert(‘系统提示‘, rowData.username +‘保存成功!‘, ‘info‘, function(btn){
                            //回调函数
                            dataGridOper.datagrid(‘load‘);
                        });
                    }
                    else {
                        $.messager.alert(‘系统提示‘, ‘保存失败:错误代码005‘, ‘error‘);
                        //回滚
                        dataGridOper.datagrid(‘rejectChanges‘);
                    }
                    editorRow = -1;
                },
                error: function(XMLHttpRequest, textStatus, errorThrown){
                    $.messager.alert(‘系统提示‘, ‘保存失败:错误代码007‘ + textStatus, ‘info‘)
                }
            });
            }
            var urlData2;
           if (operator == "updateData") {
                urlData2 = "oid=" + rowData.oid + ‘    gender="‘ + rowData.gender + ‘",phone="‘ + rowData.phone+‘"‘;
                
                console.info(urlData2);
                $.ajax({
                type: "POST",
                url:  "http://127.0.0.1:9999/zhangdaicong/crud/save2",
                data:{updatedata:urlData2},
                dataType: ‘text‘,
                success: function(msgResult){
                    console.info(msgResult);
                    if (msgResult == "success1success2") {
                        //提交自从被加载以来或最后一次调用acceptChanges以来所有更改的数据,
                        //保持该数据的状态,否则点击取消编辑,将会回到修改前的数据,相当于提交事务
                        dataGridOper.datagrid(‘acceptChanges‘);
                        //title, msg, icon, fn
                        $.messager.alert(‘系统提示‘, ‘保存成功!‘, ‘info‘, function(btn){
                            //回调函数
                            dataGridOper.datagrid(‘load‘);
                        });
                    }
                    else {
                        $.messager.alert(‘系统提示‘, ‘保存失败:错误代码009‘, ‘error‘);
                        //回滚
                        dataGridOper.datagrid(‘rejectChanges‘);
                    }
                    editorRow = -1;
                },
                error: function(XMLHttpRequest, textStatus, errorThrown){
                    $.messager.alert(‘系统提示‘, ‘保存失败:错误代码011‘ + textStatus, ‘info‘)
                }
            });
                
            


            
            }
            
            
            
            
            
            
            
            
            
            
        },
        onDblClickRow: function(rowIndex, rowData){
            //当用户双击一行时触发,参数包括,rowIndex:被双击行的索引,从 0 开始,rowData:被双击行对应的记录
            //双击行时进行编辑该行
            
            //控制一次只能编辑一行
            // if (editorRow == -1) {
                // operator = "updateData";
                //不让编辑用户名
                dataGridOper.datagrid(‘removeEditor‘, ‘username‘);
                //在第一行增加
                //队列进行编辑时必须在columns中列设置editor属性
                //开始对一行进行编辑,参数index 索引
                dataGridOper.datagrid(‘beginEdit‘, rowIndex);
                editorRow = rowIndex;
            // }
            
        },
       
        //当右键点击行时触发
        onRowContextMenu: function(e, rowIndex, rowData){
            //console.info(e);
            //阻止浏览器默认的右键事件
            e.preventDefault();
            rightIndex = rowIndex;
            //添加菜单
            $(‘#editMenu‘).menu(‘show‘, {
                left: e.pageX,
                top: e.pageY
            });
            
        }
        
    });
}

/**
 * 右键增加
 */
function addRow(){
    $(‘#idAdd‘).data().linkbutton.options.handler();
}

/**
 * 右键修改
 */
function editRow(){
    //取消选中当前页所有的行
    dataGridOper.datagrid(‘unselectAll‘);
    dataGridOper.datagrid(‘selectRow‘, rightIndex);
    
    $(‘#idEdit‘).data().linkbutton.options.handler();
}

/**
 * 右键删除
 */
function delRow(){
    //取消选中当前页所有的行
    dataGridOper.datagrid(‘unselectAll‘);
    dataGridOper.datagrid(‘selectRow‘, rightIndex);
    $(‘#idDelete‘).data().linkbutton.options.handler();
}

这是经过很多次加工修改出来的,实现的功能是:可以对记录进行增删改,并且是多记录的增删改。

 

DataGrid--多记录CRUD