ExtJS & GTGrid 簡單使用者管理

來源:互聯網
上載者:User

前段學了小胖的GTGrid,很方便實用。最近在學習Extjs.
做了個CRUD的Demo,包括Extjs版和GTGrid版,做的比較
粗糙,希望對大家有一些協助。

部分源碼:

<%@ page language="java" pageEncoding="GBK"%><%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><c:set var="ctx" value="${pageContext.request.contextPath}"/><html>  <head>      <title>使用者管理首頁</title><link rel="stylesheet" type="text/css" href="js/ext-2.2/resources/css/ext-all.css" /><script type="text/javascript" src="js/ext-2.2/adapter/ext/ext-base.js"></script><script type="text/javascript" src="js/ext-2.2/ext-all.js"></script><style type="text/css">.x-panel-body p {        margin:5px;    }    .x-column-layout-ct .x-panel {        margin-bottom:5px;    }    .x-column-layout-ct .x-panel-dd-spacer {        margin-bottom:5px;    }    .settings {        background-image:url(js/ext-2.2/shared/icons/fam/folder_wrench.png) !important;    }    .nav {        background-image:url(js/ext-2.2/shared/icons/fam/folder_go.png) !important;    }.icon-grid {    background-image: url(js/ext-2.2/shared/icons/fam/grid.png) !important;}#button-grid .x-panel-body {    border: 1px solid #99bbe8;    border-top: 0 none;}.add {    background-image: url(js/ext-2.2/shared/icons/fam/add.gif) !important;}.option {    background-image: url(js/ext-2.2/shared/icons/fam/plugin.gif) !important        ;}.remove {    background-image: url(js/ext-2.2/shared/icons/fam/delete.gif) !important        ;}.save {    background-image: url(js/ext-2.2/shared/icons/save.gif) !important;}</style>  <script>    <!--    Ext.onReady(function()    {        /**Grid相關**/        Ext.QuickTips.init();        Ext.form.Field.prototype.msgTarget='side';        var newFormWin; //form視窗容器        var form1; //添加使用者的form        var form2;; //修改使用者的form                //側邊欄狀態的記錄        Ext.state.SessionProvider = Ext.extend(Ext.state.CookieProvider, {        readCookies : function(){                if(this.state){                    for(var k in this.state){                        if(typeof this.state[k] == 'string'){                            this.state[k] = this.decodeValue(this.state[k]);                        }                    }                }                return Ext.apply(this.state || {}, Ext.state.SessionProvider.superclass.readCookies.call(this));            }        });                var xg = Ext.grid;                var jsonReader = new Ext.data.JsonReader( {            root : 'list',  //返回的資料集合            totalProperty : 'totalCount', //總記錄數            successProperty : '@success' //成功標記        }, [ {            name : 'id', //grid中的dataIndex            mapping : 'id', //返回的資料中的欄位名            type : 'int' //類型,預設為string類型        }, {            name : 'username',            mapping : 'username'        }, {            name : 'age',            mapping : 'age',            type : 'int'        },        {            name : 'ramark',            mapping : 'remark'        }]);                // Store        var ds = new Ext.data.Store( {            proxy : new Ext.data.HttpProxy( {                url : '${ctx}/UserServlet?method=getAll'            }),            reader : jsonReader        });        ds.setDefaultSort('id', 'asc');                /**    ***CRUD Grid    ****/        //自訂的checkbox列選擇    var sm = new xg.CheckboxSelectionModel({        listeners: //添加監聽器         {          //行選擇事件          rowselect : function (sm, rowIndex, keep, rec) //行選中事件          {                //得到ext組件用Ext.getCmp('id')                var btn = Ext.getCmp('tbar1');                //選擇數量大於2,禁用修改按鈕                if(sm.getCount() != 1)                {                      btn.disable();                }                else                {                    btn.enable();                }          },          //取消選擇事件          rowdeselect : function (sm, rowIndex, keep, rec) //行選中事件          {                //得到ext組件用Ext.getCmp('id')                var btn = Ext.getCmp('tbar1');                //數量等於1啟動修改按鈕                if(sm.getCount() == 1)                {                      btn.enable();                }                else                {                      btn.disable();                }          }        }            });     //初始化Grid    var grid = new xg.GridPanel({        id:'user-grid',        width:780,        height:450,        frame:true,        title:'簡易使用者管理',        iconCls:'icon-grid',        hidden: true,        store: ds, //資料倉儲        renderTo: document.body,        //列        cm: new xg.ColumnModel([            sm,            {id:'id',header: "索引", width: 40, sortable: true, dataIndex: 'id'},            {header: "使用者名稱", width: 20, sortable: true,  dataIndex: 'username'},            {header: "年齡", width: 20, sortable: true, dataIndex: 'age'},            {header: "備忘", width: 20, sortable: true, dataIndex: 'remark'}        ]),                sm: sm,        viewConfig: {            forceFit:true        },        //分頁工具列        bbar : new Ext.PagingToolbar({                pageSize : 10,                store : ds,                displayInfo : true,                displayMsg : '顯示 {0}-{1}條 / 共 {2} 條',                emptyMsg : "無資料。"            }),                    //上置內嵌工具列(按鈕)        tbar:[{            text:'添加',            tooltip:'添加一行新資料',            iconCls:'add',            handler : function()            {                add();            }        }, '-', {            text:'修改',            tooltip:'修改一條資料',            iconCls:'option',            id : 'tbar1',            handler : function()            {                modify();            }        },'-',{            text:'刪除',            tooltip:'刪除資料',            iconCls:'remove',            handler : function()             {                remove();            }        }]           });        //載入資料    ds.load({params:{start:0, limit:10}});        //渲染Grid    grid.render();            //添加使用者的函數          var add = function()          {                newFormWin = new Ext.Window({                    layout : 'fit',                    width : 400,                    height : 300,                    closeAction : 'hide',                    plain : true,                    title : '使用者管理',                    items : form1                });            newFormWin.show();          }                  //修改使用者的函數          var modify = function()           {            var _record = grid.getSelectionModel().getSelected();            if (!_record)            {                Ext.Msg.alert('請選擇要修改的一項!');            }            else            {                myFormWin();                form2.form.load                ({                    url : '${ctx}/UserServlet?method=getById&id='+ _record.get('id'),                    waitMsg : '正在載入資料',                                        failure : function() {                        Ext.Msg.alert('載入失敗');                    },                    success : function() {                        //Ext.Msg.alert('載入成功!');                    }                });            }        }        //修改使用者的表單         var myFormWin = function() {                newFormWin = new Ext.Window({                    layout : 'fit',                    width : 400,                    height : 300,                    closeAction : 'hide',                    plain : true,                    title : '修改使用者',                    items : form2                });            newFormWin.show('');        }                /*注意JsonReader要放在Form上面,資料的載入順序問題*/        var jsonFormReader = new Ext.data.JsonReader( {            root : 'list',            totalProperty : 'totalCount',            successProperty : '@success'        }, [        {            name : 'id',            mapping : 'id',            type : 'int',        },         {            name : 'username',            mapping : 'username'        }, {            name : 'age',            mapping : 'age',            type : 'int'        }, {            name : 'remark',            mapping : 'remark'        }]);                //添加使用者的Form          form1 = new Ext.FormPanel({            labelWidth : 75,            frame : true,            title : '添加使用者',            bodyStyle : 'padding:5px 5px 0',            width : 350,            waitMsgTarget : true,            url : '${ctx}/UserServlet?method=save',            defaults :             {                width : 230            },            defaultType : 'textfield',            items : [            {                fieldLabel : '使用者名稱',                name : 'username', //後台得到資料用                allowBlank : false,                blankText : '使用者名稱不可為空'            }, {                xtype : 'numberfield',                maxValue : 100,                maxText : '年齡不能超過100歲',                minValue : 1,                minText : '年齡不能小於1歲',                fieldLabel : '年齡',                name : 'age',                allowBlank : false,                blankText : '年齡不可為空'            }, new Ext.form.TextArea( {                fieldLabel : '備忘',                name : 'remark',                growMin : 234,                maxLength : 50,                maxLengthText : '最大長度不能超過50個字元!'            })],            buttons : [ {                text : '儲存',                disabled : false,                handler : function()                {                                        if(form1.form.isValid())                    {                            form1.form.submit(                        {                            url : '${ctx}/UserServlet?method=save',                            success : function(from, action)                             {                                Ext.Msg.alert('添加使用者成功!');                                ds.load({                                    params : {                                        start : 0,                                        limit : 10                                    }                                });                            },                            failure : function(form, action) {                                Ext.Msg.alert('添加使用者失敗!');                            },                            waitMsg : '正在儲存資料,稍後'                        });                        newFormWin.hide();                    }                    else                    {                        Ext.Msg.alert('請確認您已經的資訊是否已經填寫成功!');                    }                }            }, {                text : '取消',                handler : function()                 {                     form1.form.reset();                }            }]        });                //修改使用者的Form          form2 = new Ext.FormPanel({            labelWidth : 75,            frame : true,            title : '修改使用者',            bodyStyle : 'padding:5px 5px 0',            width : 350,            waitMsgTarget : true,            url : '${ctx}/UserServlet?method=update',            reader : jsonFormReader, //為Form指定reader,修改用            defaults :             {                width : 230            },            defaultType : 'textfield',            items : [            {                xtype: 'hidden',                name : 'id'            },            {                fieldLabel : '使用者名稱',                name : 'username', //後台得到資料用                allowBlank : false,                blankText : '使用者名稱不可為空'            }, {                xtype : 'numberfield',                maxValue : 100,                maxText : '年齡不能超過100歲',                minValue : 1,                minText : '年齡不能小於1歲',                fieldLabel : '年齡',                name : 'age',                allowBlank : false,                blankText : '年齡不可為空'            }, new Ext.form.TextArea( {                fieldLabel : '備忘',                name : 'remark',                growMin : 234,                maxLength : 50,                maxLengthText : '最大長度不能超過50個字元!'            })],            buttons : [ {                text : '修改',                disabled : false,                handler : function()                {                                        if(form2.form.isValid())                    {                            form2.form.submit(                        {                            success : function(from, action)                             {                                Ext.Msg.alert('修改使用者成功!');                                ds.load({                                    params : {                                        start : 0,                                        limit : 10                                    }                                });                            },                            failure : function(form, action) {                                Ext.Msg.alert('修改使用者失敗!');                            },                            waitMsg : '正在儲存資料,稍後'                        });                        newFormWin.hide();                    }                    else                    {                        Ext.Msg.alert('請確認您已經的資訊是否已經填寫成功!');                    }                }            }, {                text : '取消',                handler : function()                 {                     form2.form.reset();                }            }]        });                //刪除事件        var remove = function()         {            var _record = grid.getSelectionModel().getSelected();            if (_record)             {                Ext.MessageBox.confirm('確認刪除', '你確認要刪除選擇的資料嗎?', function(btn)                 {                    if (btn == "yes") {                        var m = grid.getSelections();                        var jsonData = "";                        for (var i = 0, len = m.length;i < len; i++)                         {                            var ss = m[i].get("id"); //使用者id , "id" 欄位名                            if (i == 0) {                                jsonData = jsonData + ss;                            } else {                                jsonData = jsonData + "," + ss;                            }                            //在資料來源裡刪除                            ds.remove(m[i]);                            //刪除資料庫相應記錄                            Ext.Ajax.request({                               url: '${ctx}/UserServlet?method=remove&id='+ss                            });                        }                                                ds.load({                            params : {                                start : 0,                                limit : 10,                                delData : jsonData                            }                        });                                            }                });            }             else             {                Ext.Msg.alert('請選擇要刪除的資料項目!');            }        };        /***/    Ext.state.Manager.setProvider    ( new Ext.state.SessionProvider({state: Ext.appState}));            // tabs for the center        var tabs = new Ext.TabPanel({            region    : 'center',            margins   : '3 3 3 0',             activeTab : 0,            defaults  : {                autoScroll : true            },            items     : [{                title    : 'ExtJS版',                contentEl: 'user-grid' //要填充的html id             },{                title    : 'GTGrid版',                html     : 'GTGrid暫不支援與Extjs的整合(window),<a href="${ctx}/gt.jsp">點此顯示我做的例子</>'             },{                 title    : '更多關注',                html     : '更多內容可關注<a href="http://www.blogjava.net/supercrsky">我的部落格</a>'            }]        });        // Panel for the west        var nav = new Ext.Panel({            title       : '菜單目錄',            region      : 'west',            split       : true,            width       : 200,            collapsible : true,            margins     : '3 0 3 3',            cmargins    : '3 3 3 3',            layout:        'accordion',                layoutConfig:{                    animate:true                },             items: [{                    html: Ext.example.shortBogusMarkup,                    title:'使用者管理',                    autoScroll:true,                    border:false,                    iconCls:'nav'                },{                    title:'使用者配置',                    html: Ext.example.shortBogusConfig,                    border:false,                    autoScroll:true,                    iconCls:'settings'                }]        });         var win = new Ext.Window({            title    : '使用者管理微型系統',            closable : true,            maximizable : true,            minimizable : true,            width    : '100%',            height   : '100%',            plain    : true,            layout   : 'border',            closable : false,            items    : [nav, tabs]        });                win.show();        win.maximize();        });    --></script>        </head>  <body>    <!-- 側邊欄使用的js -->  <script type="text/javascript" src="js/ext-2.2/shared/examples.js"></script>  </body></html>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.