温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

easyui datagrid 增删改查

发布时间:2020-07-10 20:18:08 来源:网络 阅读:739 作者:fiybird 栏目:编程语言

前台显示页面:grid.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link href="easyui/css/themes/default/easyui.css" rel="stylesheet" type="text/css" />
    <link href="easyui/css/themes/icon.css" rel="stylesheet" type="text/css" />
    <link href="easyui/css/demo.css" rel="stylesheet" type="text/css" />
    <link href="easyui/css/dlg.css" rel="stylesheet" type="text/css" />
    <script src="easyui/js/jquery-1.8.2.min.js" type="text/javascript"></script>
    <script src="easyui/js/jquery.easyui.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $("#tab").datagrid({
                title: "学生信息",
                iconCls: "icon-save",
                width: 600,
                height: 300,
                collapsible: true,
                autoRowHeight: true,
                striped: true,
                queryParams: { "action": "query" },
                url: "grid.ashx",
                frozenColumns: [[{ field: "chk", "checkbox": true}]],
                columns: [[
                    { field: 'JSON_no', title: "编号", width: 80 },
                    { field: 'JSON_name', title: "姓名", width: 100 },
                    { field: 'JSON_pwd', title: "密码", width: 100 },
                    { field: 'JSON_sex', title: "性别", width: 100 },
                    { field: 'JSON_age', title: "年龄", width: 100 },
                    { field: 'JSON_address', title: "住址", width: 100 },
                    ]],
                //                toolbar:"#tool",
                toolbar:[{
id:'btnadd',
text:'添加',
iconCls:'icon-add',
handler:function(){
$('#btnsave').linkbutton('enable');
add_dg();
}
},{
id:'btnedit',
text:'编辑',
iconCls:'icon-edit',
handler:function(){
$('#btnsave').linkbutton('enable');
edit_dg();
}
},{
id:'btncut',
text:'删除',
iconCls:'icon-no',
handler:function(){
$('#btnsave').linkbutton('enable');
dele_dg();
}
}],
                pagination: true,
                rownumbers: true,
                singleSelect:true
            });
            //////////////分页//////////////////
            $("#tab").datagrid('getPager').pagination({
                beforePageText: '当前第',
                afterPageText: '页,共{pages}页',
                displayMsg: ' 当前显示{from} - {to} 条记录  共 {total}条记录',
                pagesize: 10, //页面大小
                pageList:[10,15,20,30]
            });
        })
        //////////////////////删除/////////////////
        function dele_dg() {
            //**********返回选中的复选框,返回值是数组(object类型)
            var checked = $("#tab").datagrid('getChecked');
            if (checked[0] != null) {
                var v = '';
                for (var i = 0; i < checked.length; i++) {
                    v += checked[i].JSON_id + ',';
                }
                //************所有选中记录的id和','组成的字符串
                var str = v.substring(0, v.length - 1);                  
                $.post("grid.ashx", {"action":"del", id: str }, function (data) {
                    $.messager.alert('提示', data, 'info', function () { $("#tab").datagrid("reload"); });
                });
            }
        }
        ////////////////////////////添加///////////////////
        function add_dg() {
            //*********************$('#fm')[0](转化为dom对象)先重置表单以免编辑功能的影响
            $('#fm_dg')[0].reset();                   
            $('#dd_dg').show();
            $('#dd_dg').dialog({
                title: '记录修改',
                width: 400,
                height: 200,
                closed: false,
                cache: false,
                modal: true,
                buttons: [{
                    text: '保存',
                    iconCls: 'icon-save',
                    handler: function () {
                        var param = $("#fm_dg").serialize();
                        //解决中文乱码的
                       var params = decodeURIComponent(param, true);
                       $.post("grid.ashx", { "action": "add", data: params }, function (data) {
                           if (data == 'ok') {
                               $.messager.show({
                                   title: 'success',
                                   msg: '插入成功!'
                               });
                               $('#tab').datagrid('reload');
                           } else {
                               $.messager.show({
                                   title: 'Error',
                                   msg: '插入失败!'
                               });
                           }
                           $('#tab').datagrid('reload');
                            $('#dd_dg').window('close');
                        });
                    }
                }, {
                    text: '关闭',
                    iconCls: 'icon-cancel',
                    handler: function () {
                        $('#dd_dg').window('close');
                    }
                }]
            });
        }
        /////////////////////////////修改//////////////////////////
        function edit_dg() {
            var selected = $('#tab').datagrid('getSelected');
            if (selected != null) {
                $('#dd_dg').show();
                //***********将表格中选中的一条记录值传到编辑窗口
                $('#id').val(selected.JSON_id);
                $("#no").val(selected.JSON_no);
                $('#name').val(selected.JSON_name);
                $('#pwd').val(selected.JSON_pwd);
                //显示下拉框的选中项
                if (selected.JSON_sex == "男") {
                    $("#sex").find("option").eq(0).attr("selected", "selected");
                } else {
                    $("#sex").find("option").eq(1).attr("selected", "selected");
                }
                $('#age').val(selected.JSON_age);
                $('#address').val(selected.JSON_address);
                $('#dd_dg').dialog({
                    title: '记录修改',
                    width: 400,
                    height: 200,
                    closed: false,
                    cache: false,
                    modal: true,//显示遮罩层
                    buttons: [{
                        text: '保存',
                        iconCls: 'icon-save',
                        handler: function () {
                            var param = $("#fm_dg").serialize();
                            var params = decodeURIComponent(param, true);
                            $.post("grid.ashx", { "action":"edit",data:params}, function (data) {
                                if (data == 'ok') {
                                    $.messager.show({
                                        title: 'success',
                                        msg: '修改成功!'
                                    });
                                    $('#tab').datagrid('reload');
                                } else {
                                    $.messager.show({
                                        title: 'Error',
                                        msg: '修改失败!'
                                    });
                                }
                                $('#dg').datagrid('reload');
                                $('#dd_dg').window('close');
                            });
                        }
                    }, {
                        text: '关闭',
                        iconCls: 'icon-cancel',
                        handler: function () {
                            $('#dd_dg').window('close');
                        }
                    }]
                });
            }
        }
    </script>
</head>
<body>
<!-- datagrid -->
<table id="tab"></table>
<!-- 添加窗体 -->
<div id="dd_dg"  >
    <form id="fm_dg" method="post" action="grid.ashx">
        <input type="hidden" name="id" id="id"/>
        编号:<input type="text" name="no" id="no" class="easyui-validatebox"  required="true"/><br/>
        姓名:<input type="text" name="name" id="name" class="easyui-validatebox"  required="true"/><br/>
        密码:<input type="password" name="pwd" id="pwd" class="easyui-validatebox"  required="true"/><br/>
        性别:<select name="sex" id="sex">
                      <option value="1">男</option>
                      <option value="0">女</option>
                </select><br/>
        年龄:<input type="text" name="age" id="age" class="easyui-validatebox"  required="true"/><br/>
        住址:<input type="text" name="address" id="address" class="easyui-validatebox"  required="true"/><br/>
    </form>
</div>
</body>
</html>
//后台数据处理页面grid.ashx
public class grid : IHttpHandler
    {
        public void Proce***equest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string action = context.Request["action"].ToString();
            switch (action)
            {
                case "query":
                    Query();
                    break;
                case "del":
                    Del();
                    break;
                case "add":
                    Add();
                    break;
                case "edit":
                    Edit();
                    break;
            }
        }
        /// <summary>
        /// 查询并分页
        /// </summary>
        private void Query()
        {
            string str = string.Empty;
             string rows = HttpContext.Current.Request["rows"].ToString();  //获取datagrid传来的行数
            string page = HttpContext.Current.Request["page"].ToString(); //获取datagrid传来的页码 当前页
            // GetTablebyproc上篇文章的调用带参数的存储过程,返回datat
            DataTable dt1 = SqlHelper.GetTablebyproc("pageFileter", int.Parse(rows), int.Parse(page), "stu");
            DataTable dt = SqlHelper.GetTable("select * from stu");
            str = JSonHelper.CreateJsonParameters(dt1, true, dt.Rows.Count);
            HttpContext.Current.Response.Write(str);
        }
        /// <summary>
        /// 删除一行数据
        /// </summary>
        private void Del()
        {
            string str = "删除失败";
            string id = HttpContext.Current.Request["id"] != "" ? HttpContext.Current.Request["id"].ToString() : "";
            if (id != string.Empty)
            {
                int num = SqlHelper.DelData("stu", id);
                if (num > 0)
                {
                    str = string.Format("删除成功,本次共删除{0}条", num.ToString());
                }
                else
                {
                    str = "删除失败";
                }
            }
            HttpContext.Current.Response.Write(str);
        }
        /// <summary>
        /// 添加一条数据
        /// </summary>
        private void Add()
        {
            StringBuilder sb = new StringBuilder();
            foreach (string s in HttpContext.Current.Request.Form.AllKeys)
            {
                sb.AppendFormat("{0}: {1}\n", s, HttpContext.Current.Request.Form[s]);
            }
            string str = sb.ToString();
            string[] str1 = str.Split('&');
            string no = str1[1].Split('=')[1];
            string name = str1[2].Split('=')[1];
            string pwd = str1[3].Split('=')[1];
            string sex = str1[4].Split('=')[1]=="1"?"男":"女";
            int age = int.Parse(str1[5].Split('=')[1]);
            string add = str1[6].Split('=')[1];
            string address = add.Substring(0, add.Length - 1);
            string sql = string.Format("insert into stu values('{0}','{1}','{2}','{3}',{4},'{5}')", no, name, pwd, sex, age, address);
            int count = 0;
            count = SqlHelper.ExeNonQuery(sql, CommandType.Text, null) ? 1 : 0;
            if (count > 0)
            {
                HttpContext.Current.Response.Write("ok");
            }
            else
            {
                HttpContext.Current.Response.Write("no");
            }
        }
        /// <summary>
        /// 修改一条数据
        /// </summary>
        private void Edit()
        {
            StringBuilder sb = new StringBuilder();
            foreach (string s in HttpContext.Current.Request.Form.AllKeys)
            {
                sb.AppendFormat("{0}: {1}\n", s, HttpContext.Current.Request.Form[s]);
            }
            string str = sb.ToString();
            string[] str1 = str.Split('&');
            int id = int.Parse(str1[0].Split('=')[1]);
            string no = str1[1].Split('=')[1];
            string name = str1[2].Split('=')[1];
            string pwd = str1[3].Split('=')[1];
            string sex = str1[4].Split('=')[1] == "1" ? "男" : "女";
            int age = int.Parse(str1[5].Split('=')[1]);
            string add = str1[6].Split('=')[1];
            string address = add.Substring(0, add.Length - 1);
            string sql = string.Format("update stu set no='{0}',name='{1}',pwd='{2}',sex='{3}',age={4},address='{5}' where id={6}", no, name, pwd, sex, age, address, id);
            int count = 0;
            count = SqlHelper.ExeNonQuery(sql, CommandType.Text, null) ? 1 : 0;
            if (count > 0)
            {
                HttpContext.Current.Response.Write("ok");
            }
            else
            {
                HttpContext.Current.Response.Write("no");
            }
        }


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI