欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

extJs 常用到的增,删,改,查操作代码

程序员文章站 2022-06-17 17:50:10
复制代码 代码如下:<%@ page language="java" import="java.util.*" pageencoding="utf-8"%> &...
复制代码 代码如下:

<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>

<html>
    <head>
        <title>extjs中常用到的增删改查操作的示例代码</title>
        <!-- commonjs.jsp 为 extjs 引入的路径 -->
        <%@ include file="../extjs/commonjs.jsp"%>
        <script type="text/javascript"><!--
        /**
        * 作     者: 花 慧
        * 时     间: 2009年12月22日
        * 内 容: extjs中常用到的增,删,改,查操作
        */    

        //设置每页显示的行数默认为10

        var query_page_size = 10;

        /**
        * searchqueryform():绘制查询表单
        */
        function searchqueryform()
        {
         //form 使用的时候建议设为局部变量,可以通过ext.getcmp(“”)去获取form

         var queryform = null;
            queryform = new ext.formpanel({
                id:'queryform', //指定queryform的id
                renderto:'searchpanel', //指向form所在的div层
                labelwidth:70, //label标签的width占页面的百分比
                region:'north',
                border:false, //以显示面板的body元素的边界,虚假隐藏起来(默认为true)
                badyborder:false, //显示面板的body元素,假以隐藏它(默认为true的内部边界)
                labelalign:'right', //label标签的对齐方式
                frame:true, //自定义面板的圆形边界,边界宽度1px。默认为false
                title:'用户信息查询', //form的标题
                /**
                *buttons:在formpanel中按钮的集合
                */
                buttons:[{handler:addform,text:'新增'},
                        {handler:submitform,text:'查询'},
                        {handler:resetform,text:'重置'}],
             /**
             * items: 在formpanel中不可缺少的部分
             */
             items:[{
         /**
              * layout:extjs容器组件,可以设置它的显示风格
              * 它的有效值有absolute,accordion,anchor,border,card,fit,form and table 共9种
              */
                 layout:'column',
                 items:[
                     {
                         columnwidth:.5,
                         layout:'form',
                         items:{
                             name:'userid',
                             hiddenname:'userid',
                             xtype:'textfield',
                             fieldlabel:'用户编码',
                             maxlength:'50',
                             vtype:'specialchar',
                             anchor:'80%'
                         }
                     },{
                         columnwidth:.5,
                         layout:'form',
                         items:{
                             name:'username',
                             hiddenname:'username',
                             xtype:'textfield',
                             fieldlabel:'用户名称',
                             maxlength:'100',
                             vtype:'specialchar',
                             anchor:'80%'
                         }
                     }
                 ]
             }]
            });
        }
        /**
        * showuserform():绘制添加表单
        */
        function showuserform()
        {
         //将变量定义成局部变量,避免每次都生成一个新对象

            var userform = null;
            userform = new ext.formpanel({
                id:'conditionform',
                labelwidth:'80',
                labelalign:'right',
                border:false,
                bodyborder:false,
             frame:true,
             items:[
                 layout:'column',
                 items:[
                 {
                     columnwidth:'.8',
                     items:{
                         name:'userinfo.userid',
                         hiddenname:'userinfo.userid', //hiddenname动态的绑定数据库中对应的字段
                         xtype:'textfield', //xtype可以分为三类,textfield为表单域的控件
                         fieldlabel:'用户编码<font color=red>*</font>',//控件前的文本说明
                         labelseparator:'',
                         blanktext : '填写用户编码', //为空的文本框提示信息
                         allowblank:false,      //不允许为空
                         maxlength:'50',      //文本框允许输入的最大的长度,最小的minlength
                         vtype:'specialchar',
                         anchor:'80%'
                     }
                 },{
                     columnwidth:'.8',
                     items:{
                         name:'userinfo.username',
                         hiddenname:'userinfo.username',
                         xtype:'textfield',
                         fieldlabel:'用户姓名<font color=red>*</font>',
                         labelseparator:'',
                         blanktext:'填写用户姓名',
                         allowblank:false,
                         maxlength:'100',
                         vtype:'specialchar',
                         anchor:'100%'
                     }
                 },{
                     columnwidth:'.8',
                     items:{
                         name:'userinfo.pwd',
                         hiddenname:'userinfo.pwd',
                         xtype:'textfield',
                         inputtype:'password',
                         fieldlabel:'用户密码<font color=red>*</font>',
                         labelseparator:'',
                         blanktext:'填写用户密码',
                         allowblank:false,
                         maxlength:'12',
                         minlength:'6',
                         value:'123456', //用户默认的秘密
                         anchor:'100%'
                     }
                 },{
                     columnwidth:'.8',
                     items:{
                         name:'rpwd',
                         hiddenname:'rpwd',
                         xtype:'textfield',
                         inputtype:'password',
                         fieldlabel:'确认密码<font color=red>*</font>',
                         labelseparator:'',
                         blanktext:'二次输入的秘密要相同',
                         allowblank:false,
                         vtype:'pwdrange',
                         pwdrange:{begin:'userinfo.pwd',end:'rpwd'},
                         maxlength:'12',
                         anchor:'100%'
                     }
                 }]
             ]
            });
        }
        /**
        * edituserform():绘制修改表单
        */
        function edituserform(){
            //将变量定义成局部变量,避免每次都生成一个新对象

            var userform = null;
            userform = new ext.formpanel({
                id:'editform',
                labelwidth:'80',
                labelalign:'right',
                border:false,
                bodyborder:false,
             frame:true,
             items:[
                 layout:'column',
                 items:[
                 {
                     columnwidth:'.8',
                     items:{
                         name:'userinfo.userid',
                         hiddenname:'userinfo.userid', //hiddenname动态的绑定数据库中对应的字段
                         xtype:'textfield', //xtype可以分为三类,textfield为表单域的控件
                         fieldlabel:'用户编码', //控件前的文本说明
                         labelseparator:':',
                         readonly:true, //文本框只读
                 disabled:true, //文本框灰色,区别与其他的文本框颜色
                         blanktext : '填写用户编码', //为空的文本框提示信息
                         allowblank:false,      //不允许为空
                         maxlength:'50',      //文本框允许输入的最大的长度,最小的minlength
                         //字母开头,且只能存在字母与数字长度为2到12位

                         regex : /^[a-za-z]{1}([a-za-z0-9]|[_]){1,11}$/,
                 regextext : '用户编码必须以字母开头,长度2-12位!',
                         anchor:'90%'
                     }
                 },{
                     columnwidth:'.8',
                     items:{
                         name:'userinfo.username',
                         hiddenname:'userinfo.username',
                         xtype:'textfield',
                         fieldlabel:'用户姓名',
                         labelseparator:':',
                         blanktext:'填写用户姓名',
                         allowblank:false,
                         maxlength:'100',
                         //只含有汉字、数字、字母、下划线不能以下划线开头和结尾

                         regex : /^(?!_)(?!.*?_$)[a-za-z0-9_\u4e00-\u9fa5]+$/,
                 regextext : '只含有汉字、数字、字母、下划线不能以下划线开头和结尾!',
                         anchor:'90%'
                     }
                 },{
                  columnwidth:'.2',
         items:{
     hiddenname:"infofill",
         name:"infofill",
         xtype:'label',
         html:'<font color=red>*</font>',
         labelseparator:'',
         anchor:'100%'
         }
                 },{
                     columnwidth:'.8',
                     items:{
                         name:'userinfo.pwd',
                         hiddenname:'userinfo.pwd',
                         xtype:'textfield',
                         inputtype:'password',
                         fieldlabel:'用户密码<font color=red>*</font>',
                         labelseparator:':',
                         blanktext:'填写用户密码',
                         allowblank:false,
                         maxlength:'12',
                         minlength:'6',
                         anchor:'90%'
                     }
                 },{
                  columnwidth:'.2',
         items:{
     hiddenname:"infofill",
         name:"infofill",
         xtype:'label',
         html:'<font color=red>*</font>',
         labelseparator:'',
         anchor:'100%'
         }
                 },{
                     columnwidth:'.8',
                     items:{
                         name:'rpwd',
                         hiddenname:'rpwd',
                         xtype:'textfield',
                         inputtype:'password',
                         fieldlabel:'确认密码<font color=red>*</font>',
                         labelseparator:':',
                         blanktext:'二次输入的秘密要相同',
                         allowblank:false,
                         //在extcommon.js文件中定义二次输入的密码相同验证pwdrange

                         // vtype为验证的方法,如果是通用的验证,请在方法中定义,如果是特例,可以使用regex
                         vtype:'pwdrange',
                         pwdrange:{begin:'userinfo.pwd',end:'rpwd'},
                         maxlength:'12',
                         anchor:'90%'
                     }
                 },{
                  columnwidth:'.2',
         items:{
     hiddenname:"infofill",
         name:"infofill",
         xtype:'label',
         html:'<font color=red>*</font>',
         labelseparator:'',
         anchor:'100%'
         }
                 }]
             ]
            });
        }
        /**
        * onready:该文件准备好(在onload和图像加载之前)
        */
        ext.onready(function(){

            searchqueryform();
            //获取查询form

            var queryform = ext.getcmp("queryform").getform();
         /**
         * layout设置为border表示页面将划分为东南西北中五个部分
         * 这里表示centerpanel放在中间
         */
            var layout = new ext.viewport({
                layout:'border',
                defaluts:{border:false,bodyborder:false,activetab:0},
          items:[queryform,{id:'centerpanel',region:'center',height:document.body.clientheight,contentel:'maindiv'}]
            });
            //页面加载的时候,默认数据查询页面显示用户信息列表

            submitform();
        });

        //查询信息
        var store = new ext.data.store({
            url:'../user/dogetpagelist.action', //action的路径
            reader:new ext.data.jsonreader({
                root:'userlist', //从struts2.0里面传递过来的参数:用户的集合
                totalproperty:'rowtotal', //从struts2.0里面传递过来的参数:总共的信息的行数
                id:'userid',
                successpropery:'success'},
                ['userid','username','pwd']
            )
        });

        /**
        * callback:调用的函数
        */
        function getmsg()
        {

        }
        /**
        * 模糊查询
        */
        function submitform()
        {
         //初始化grid
            var grid = null;
            //复选框
            var sm = new ext.grid.checkboxselectionmodel({
                dataindex:'id',
                width:'20'
            });
            /**
         *  sortabel:(可选)如果真要排序允许在此列
         *  renderer:(可选)用于生成给定数据值单元格的html标记的功能。如果没有指定,默认渲染器使用的原始数据值。
         * 在renderer:function createbutton(参数)这里的参数可以没有或多个
         *  鼠标移动图片上变成"手"是:style="cursor:hand"
         */
            var colm = new ext.grid.columnmodel(
                [sm,{header:'用户账号',dataindex:'userid',align:'center',sortable:true},
                {header:'用户姓名',dataindex:'username',align:'center',sortabel:true},
                {header:'删除',dataindex:'id',align:'center',renderer:function createbutton(){
                    return '<img alt="删除" style="cursor:hand" style="cursor:hand" src="../images/hh_framework/ico_delete.gif" src="images/hh_framework/ico_delete.gif" />';}},
                {header:'编辑',dataindex:'userid',align:'center',renderer:function createbutton(userid, metadata, record){
                    return '<a style="cursor:hand" style="cursor:hand" onclick=updateform('+userid+') >'+record.get('username')+'的信息修改'+'</a>';}}]
            );

         //获取查询表单

            var form = ext.getcmp("queryform").getform();

            //判断是否通过验证,如果没有请直接关闭
            if(!form.isvalid())
            {
                ext.msg.alert("系统提示","查询数据不正确,请确认输入!");
                return ;
            }
            //差选queryform中查询的数据参数

            store.baseparams = form.getvalues();
            /**
            * getlimitcount():获取分页每页行数,如果不传值,则会取默认值
            * start表示读取数据的起始位置、limit表示每次读取多少条数据
            * callback:getmsg 表示回调时,执行函数 getmsg。可省略
            */

            store.load({params:{start:0,limit:getlimitcount()}, callback:getmsg});
            if(grid == null)
            {
                grid = new ext.grid.editorgridpanel({
                    renderto:"maindiv", //grid查询结果指向显示的div层
                    title:"用户查询结果", //grid标题
                    width:document.body.clientwidth, //设置grid的width的值
                    hight:document.doby.clienthight-100,//设置hight的值
                    viewconfig:{forcefit:true}, //设置列数的充满窗口
                    loadmask:true,                //在加载数据时的遮罩效果
                    striperows:true, //隔行换色
                    region:'center', //这个是设置在viewport中显示的位置
                    cm:colm, //定义的列
                    ds:store, //定义的数据源
                    border:false,
                    bodyborder:false,
                    sm:sm, //定义的复选框

                    //listeners:包含一个或多个事件处理程序被添加到这个对象初始化过程中

                    listeners:{cellclick:renderpage},
                    /**
                 * bbar: new ext.pagingtoolbar部分是定义分页工具栏,
                 * 这里的分页控件栏还用到了1个自己定义的插件,就是可以选择每页显示多少条的
                    * plugins : [new ext.ux.pagesizeplugin()],参考ext的api
                 * 要实现分页,后台必须有total属性,表示共多少条数据
                 */

                    bbar:new ext.pagingtoolbar({
                        items:[{
                            xtype:'button',
                            text:'删除所选',
                            handler:deluserall, //自定义执行动
                            pressed:true
                        }],
                        id:'pagetoolbar',
                        pagesize:query_page_size, //每页的行数默认为:query_page_size
                        store:store,
                        displayinfo:true,
                        displaymsg:'显示第{0}条到{1}条记录,共{2}条记录',
                        emptmsg:'没有记录',
                        plugins:[new ext.ux.pagesizeplugin()]
                    })
                });
            }
            grid.render();
        }
        /**
        * 增加用户信息
        */
        function addform()
        {
            showuserform();
            //获取绘制用户窗口的form

            var userform = ext.getcmp("conditionform").getform();
            //初始化用户添加的窗口的id

            var adduserwin = ext.getcmp("addwin");
            if(adduserwin == null)
            {
                adduserwin = new ext.window({
                    width:500, //初始窗口的width的值
                    x:100, //窗口的初始化x方向的位置
                    y:100, //窗口的初始化y方向的位置
                    plain:true,
                    modal:true, //模式窗口,默认为false
                    closeaction:"hide", //默认窗口隐藏
                    resizable:false, //窗口的大小不允许拖动,默认为true
                    id:"addwin", //指定用户添加窗口的id
                    items:[userform],
                    buttons:[
                 {text:'保存',handler:function(){
                     if(userform.form.isvalid()){
                      userform.form.doaction('submit',{
                             url:'../user/adduser.action',
                             params:{roleid:userform.form.findfield('userid').getvalue()},
                             method:'post', //数据提交的方式:有两种get,post
                             waittitle:'提示信息', //数据提交等待的滚动条
                             waitmsg:'保存数据,请稍候...', //滚动条提示的内容
                          success:function(form,action){
                          var message = action.result.message;
                              if(message == null){
                              ext.msg.alert("提示信息","用户信息添加成功!");
                              store.reload();
                              adduserwin.hide();
                              }else{
                              ext.msg.alert("提示信息",message);
                              }
                          },
             failure:function(form,action){
             ext.msg.alert('提示信息',"新用户添加失败!");
             return;
             }
             });
                 }else {
                     ext.msg.alert("提示信息","表单有错误,请正确填写!");
                 }
                 }},
                 {handler:function(){userform.form.reset();},text:'重置'},
                 {handler:function(){adduserwin.hide();},text:'关闭'}]
                });
            }
            adduserwin.show();
        }
        /**
        * 删除用户信息
        */
        function delform(userid)
        {
            ext.msg.confirm('提示信息','你确定要执行删除操作吗?',function(btn){
                if(btn == 'yes')
                {
                     /**
                 * 数据提交的一种方式:ext.ajax.request({});
                 */
                    ext.ajax.request({
                        url:'../user/deluser.action',
                        params:{userid:userid},
                        method:'post',
                        success:function(o)
                        {
                            var info = ext.decode(o.responsetext);
                            ext.msg.alert("提示信息",info.message);
                            store.reload();
                            return ;
                        },
                        failure:function(form,action)
                        {
                            ext.msg.alert("提示信息","用户信息删除失败!");
                            return ;
                        }
                    });
                }
            });
        }
        /**
        * 批量删除事件
        */
        function deluserall()
        {
         //grid中复选框被选中的项

             var rows = grid.getselectionmodel().getselections();
             //user_id:所有选中的用户id的集合使用','隔开,初始化为空

             var user_id = '';
         for(var i = 0;i<rows.length;i++)
         {
             if(i>0)
             {
                 user_id = user_id+','+rows[i].get('userid');
             }else{
                 user_id = user_id+rows[i].get('userid');
             }
         }
         //没有选择要执行操作的对象

             if(user_id == "")
             {
                 ext.msg.alert("提示信息","请选择要删除的对象");
                 return ;
             }else{
                 ext.msg.confirm("提示信息","请确定要执行删除操作吗?",function (btn){
                     if(btn == 'yes')
                     {
                         ext.ajax.request({
                             url:"../user/delalluser.action",
                             params:{id:user_id},
                             method:'post',
                             success:function(o){
                                 var info = ext.decode(o.responsetext);
                                 ext.msg.alert("提示信息",info.message);
                                 store.reload();
                                 return ;
                             },
                             failure:function(form,action){
                                 ext.msg.alert("提示信息","用户信息删除失败!");
                             }
                         });    
                     }
                 });
             }
        }
        /**
        * 修改用户信息
        * 参数userid:修改对象的id
        */
        function updateform(userid)
        {
            edituserform();

            var userform = ext.getcmp("editform").getform();
            ext.ajax.request({
                url:'../user/dogetone.action',
                params:{userid:userid},
                method:'post',
                //从struts2.0里返回的参数

                success:function(o)
                {
                 //读取action传递过来的对象参数
                 //docode:解码(解析)一个json字符串对象

                    var user = ext.decode(o.responsetext);

                    //用户编辑窗口的打开

                    edituser(user);

                    //将对象信息显示在对应的form文本框中

                    userform.form.findfiled('userinfo.userid').setvalue(user.userinfo.userid);
                    userform.form.findfiled('userinfo.username').setvalue(user.userinfo.username);
                    userform.form.findfiled('userinfo.pwd').setvalue(user.userinfo.pwd);
                    userform.form.findfiled('rpwd').setvalue(user.userinfo.pwd);
                }
            });
        }
        /**
        * 用户信息编辑窗口
        */
        function edituser(user){
            var userform = ext.getcmp("editform").getform();
            //得到用户编辑的窗口的对象
            var edituserwin = ext.getcmp("editwin");
            //当为空的时候将进行实例化

            if(edituserwin == null)
            {
                edituserwin = new ext.window({
             id:'editwin',
                width:500,
                x:100,
                y:100,
                modal:true,
                resizable:false,
                closeaction:"hide",
                title:'用户信息修改',
                items:[userform],
                buttons:[
                    {text:'保存',handler:function(){
                        if(userform.form.isvalid())
                        {
                         /**
                         * 数据提交的第二种方式:form.doaction('submit',{});
                         */
                            userform.form.doaction('submit',{
                                url:'../user/upduser.action',
                                params:{userid:userform.form.findfield('userinfo.userid').getvalue()},
                                method:'post',
                                waittitle:'提示信息',
                                waitmsg:'数据处理中,请稍后....',
                                //从struts2.0里不需要返回的参数

                                success:function(form,action)
                                {
                                    ext.msg.alert("提示信息","用户信息修改成功!");
                                    //查询的数据集合store刷新,实现页面自动刷新的效果

                                    store.reload();
                                    //将窗口关闭时候,window. hide()方法是隐藏,因此并不会真正销毁窗口对象

                                    edituserwin.hide();
                                    return ;
                                },
                                failure:function(form,action)
                                {
                                    ext.msg.alert("提示信息","用户信息修改失败");
                                    return ;
                                }
                            });
                        }else
                        {
                            ext.msg.alert("提示信息","表单有错误,请重新填写!");
                        }
                    }},
                    {text:'关闭',handler:function(){edituserwin.hide();}}]
             });
            }
            edituserwin.show();
        }
        /**
        * 重置页面查询表单
        */
        function resetform()
        {
            ext.getcmp("queryform").getform().reset();
        }

        /**
        * 每行单元格点击事件
        */
        function renderpage(grid,rowindex,columnindex,e)
        {
         //触发事件的对象的id
            var id = grid.getstore().getat(rowindex).data['userid'];
            switch(columuindex)
            {
                case 3:delform(id);
                     break;
             /**
                *case 4:updateform(id);
                *     break;
                */
             default:break;
            }
        }

// --></script>
    </head>

    <body>
        <div id="searchpanel">
        </div>
        <div id="centerpanel">
        </div>
        <div id="maindiv"></div>
    </body>
</html>