Jquery easyui从零单排之datagrid整表编辑保存到数据库

最近一直在利用空余时间,对Jquery EasyUI进行学习。前几篇都是在讲datagrid,今天这篇还是讲它的,是对datagrid进行编辑,然后把新数据全部保存到数据库的问题。


这个地方还是花了好长的时间,主要是在前台把循环读取datagrid的数据转换为json数据,以及json传递问题。


先在前台添加datagrid,这个在这里就不用再复述了。

<head>
    <title>Start from zero</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" type="text/css" href="jquery-easyui-1.4.1/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="jquery-easyui-1.4.1/themes/icon.css">
    <link rel="stylesheet" type="text/css" href="jquery-easyui-1.4.1/demo/demo.css">
    <script type="text/javascript" src="jquery-easyui-1.4.1/jquery.min.js"></script>
    <script type="text/javascript" src="jquery-easyui-1.4.1/jquery.easyui.min.js"></script>
</head>
<body>
    <form id="fm">
    <div id="tb">
        <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-save',plain:true"
            οnclick="accept()">保存</a>
            <input type="hidden" id="text" />
    </div>
    <table id="dg" title="Client Side Pagination" toolbar="#tb" fitcolumns="true" rownumbers="true"
        showfooter="true" style="width: 640px; height: 600px" data-options="
				remoteSort:false,
                rownumbers:true,
				singleSelect:true,
				autoRowHeight:true,
				pagination:true,
                showFooter: true,
                fitColumns: true,
				pageSize:20,
                onClickRow: onClickRow">
        <thead frozen="true">
            <tr>
                <th data-options="field:'ck',checkbox:true,width:40">
                </th>
                <th data-options="field:'LoginID',width:100" sortable="true">
                    LoginID
                </th>
            </tr>
        </thead>
        <thead>
            <tr>
                <th data-options="field:'UserName',width:120,editor:'textbox'" sortable="true">
                    UserName
                </th>
                <th data-options="field:'Sex',align:'center',width:80,editor:'textbox'" sortable="true">
                    Sex
                </th>
                <th data-options="field:'Department',width:140,editor:'textbox'" sortable="true">
                    Department
                </th>
                <th data-options="field:'Age',width:80,editor:'textbox'" sortable="true">
                    Age
                </th>
            </tr>
        </thead>
    </table>
    <script type="text/javascript">
        function getData()
        {
            var lastIndex;
            $('#dg').datagrid({
                url: 'Handler2.ashx',
                method: 'get',
                striped: true,
                title: "员工列表"
            })
        }
        function onClickRow(index)
        {
            if (editIndex != index) {
                if (endEditing()) {
                    $('#dg').datagrid('selectRow', index)
            .datagrid('beginEdit', index);
                    editIndex = index;
                } else {
                    $('#dg').datagrid('selectRow', editIndex);
                }
            }
        }
        function accept()
        {
            var test="test";
            var rowsData = $('#dg').datagrid('getRows');
            var json = [];
            var loc;
            $.each(rowsData, function (i)
            {
                loc = { 
                    "ID":rowsData[i].ID,
                    "LoginID": rowsData[i].LoginID,
                    "UserName": rowsData[i].UserName,
                    "Sex": rowsData[i].Sex,
                    "Department": rowsData[i].Department,
                    "Age": rowsData[i].Age
                };
                json.push(loc);
            });
            json = JSON.stringify(json); //转换成json数据 
            //alert(json);
            $('#dg').datagrid({
                url: 'Handler2.ashx?test=' + test+ "&jj=" + json,
                method: 'get'
            })
        }
        var editIndex = undefined;
        function endEditing()
        {
            if (editIndex == undefined) { return true }
            if ($('#dg').datagrid('validateRow', editIndex)) {
                var ID = $('#dg').datagrid('getEditor', { index: editIndex, field: 'ID' });
                $('#dg').datagrid('endEdit', editIndex);
                editIndex = undefined;
                return true;
            } else {
                return false;
            }
        }
        $(function ()
        {
            getData();
        });
    </script>
    <input name="Test" id="test" type="hidden" />
    </form>
</body>
</html>

对于datagrid的可编辑,主要是在它的行单击事件中实现的,上面代码中的onClickRow(index),这个可以去详细查看官网的实例。


保存事件accept()函数才是关键,既然要重新保存数据,就要先获取整个datagrid的数据$('#dg').datagrid('getRows'),然后你要想啊,怎么才能把这些数据传递到一般处理程序那里呢,我自己原本是想把这些数据弄成一个数组传过去,可是搞了半天没成功,后面就换了思路,试试json传递,没想还成功了。

var rowsData = $('#dg').datagrid('getRows');
            var json = [];
            var loc;
            $.each(rowsData, function (i)
            {
                loc = { 
                    "ID":rowsData[i].ID,
                    "LoginID": rowsData[i].LoginID,
                    "UserName": rowsData[i].UserName,
                    "Sex": rowsData[i].Sex,
                    "Department": rowsData[i].Department,
                    "Age": rowsData[i].Age
                };
                json.push(loc);
            });
            json = JSON.stringify(json); //转换成json数据 
至于传递这里我写得有点丑,或者是丑到爆了,有会的兄弟朋友请多多指教,代码如下:

    $('#dg').datagrid({
                url: 'Handler2.ashx?test=' + test+ "&jj=" + json,
                method: 'get'
            })


然后一般处理程序,主要是就是接收json数据,然后转换json数据,用sql语句保存至数据库。

public class Handler2 : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        string text = context.Request.QueryString["test"];//前台传的标示值 

        if (string.IsNullOrEmpty(text))//当为空时,表示直接绑定datagrid
        {
            SqlHelp sqla = new SqlHelp();
            string stra = "select top 5 * from tTestTable";

            DataTable dta = sqla.GetDataTable(stra);
            sqla.SqlClose();

            string json = JsonConvert.SerializeObject(dta);

            context.Response.Write(json);
        }
        else if (text == "test")//保存数据
        {
            string josnArray = context.Request.Params["jj"].ToString();//获取传递过来的json数据
            DataTable dt = JsonConvert.DeserializeObject<DataTable>(josnArray);//把json数据转换为DataTable
               foreach (DataRow dr in dt.Rows)
            {
                SqlHelp sqla = new SqlHelp();
                string stra = "update tTestTable set UserName='" + dr["UserName"].ToString() + "' where ID='" + dr["ID"].ToString() + "'";
                bool aa = sqla.ExecuteNonQuery(stra);
                sqla.SqlClose();
            }
        }


    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

搞了这么久,功能是实现了,但是远远算不上成功,为什么呢,因为我发现了一个bug,在其他浏览器下操作都是没有问题,但是在IE下操作之后,存到数据库里该字段下的汉字都变成了问号“?”,如下图

数据表截图:



页面显示截图:


这种情况只存在于用IE浏览器操作(IE浏览器下操作,编辑汉字就会保存为这种问号“?”,数字和字母不会),用其他浏览器都正常,找了好久的问题,感觉不是数据库的问题,应该是IE的问题,原本觉得是编码的问题,我尝试了也没啥反应,所在在这里提出来,希望大家探讨下,也请教下会的朋友,谢谢。

已标记关键词 清除标记
相关推荐
<div class="post-text" itemprop="text"> <p>I am new to html & php and I appreciate your help. I am trying to accept user input into a webpage and then after the user clicks the submit button, write a new record out to MySQL. I am using Wordpress so the tags are not exactly textbook. So my first problem is that the submit button does not appear to execute the php code. I also would appreciate it if someone could check how I am passing my html field names to the php variables to make sure that I am on the right track. Thanks for your help!</p> <pre><code> <form action="employee_list.php" method="post" <input type="submit" name="passport" id="passport" action="uraction" method="post" enctype="multipart/form-data" <label for="upload" >Select Employee Passport</label><input type="file" id="upload" name="upload" accept="image/*"> <p/> <div class="form-group"> <div class="form-row"> <div class="col-md-6"> <label for="name">Employee Full Name</label> <input type="text" class="form-control" id="exampleInputName" aria-describedby="nameHelp" placeholder="Enter Full Name"> </div> <div class="col-md-6"> <label for="gender">Gender</label> <select type="text" class="form-control" id="exampleInputLastName" aria-describedby="nameHelp"> </select> </div> <div class="col-md-6"> <label for="maritalstatus">Marital Status</label> <select type="text" class="form-control" id="exampleInputLastName" aria-describedby="nameHelp"> </select> </div> <div class="col-md-6"> <label for="department">Department</label> <input type="text" class="form-control" id="Position" aria-describedby="nameHelp" placeholder="Enter The Department"> </div> <div class="col-md-6"> <label for="salary">Salary</label> <input type="number" class="form-control" id="salary" aria-describedby="nameHelp" placeholder=""> </div> <div class="col-md-6"> <label for="certificate"> Highest Certificate Acquired</label> <input type="text" class="form-control" id="salary" aria-describedby="nameHelp" placeholder="Enter Highest Certificate Acquired"> </div> </div> </div> <div class="form-group"> <label for="Email">Email Address</label> <input type="emai" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email"> </div> <div class="form-group"> <label for="address">House Address</label> <input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter House Address"> </div> <div class="form-group"> <div class="form-row"> <div class="col-md-6"> <label for="phonenumber">Phone Number</label> <input type="number" class="form-control" id="phonenumber"> </div> </form> </div> <!-- /.content-wrapper --> PHP script: <?php if(isset($_POST['submit'])) { $SQL = "INSERT INTO tbl_employee (name, gender, marital_status,department,salary,certificate, email,address,phone_number) VALUES ('$_POST[name]', '$_POST[gender]', '$_POST[marital_status],'$_POST[department]','$_POST[salary]‌​ ','$_POST[certificat‌​ e]','$_POST[email]',‌​'$_POST[address]','$‌​_POST[phone_numer]')‌​"; $result = mysql_query($SQL); } ?> </code></pre> </div>
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页