jQuery DataGrid 实现增删改查,分页

HTML:

View Code
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="keywords" content="jquery,ui,easy,easyui,web">
    <meta name="description" content="easyui help you build your web page easily!">
    <title>jQuery EasyUI CRUD Demo</title>
    <link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/icon.css">
    <link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/demo/demo.css">
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
    <script type="text/javascript" src="http://www.jeasyui.com/easyui/jquery.easyui.min.js"></script>
    <style type="text/css">
        #fm{
            margin:0;
            padding:10px 30px;
        }
        .ftitle{
            font-size:14px;
            font-weight:bold;
            color:#666;
            padding:5px 0;
            margin-bottom:10px;
            border-bottom:1px solid #ccc;
        }
        .fitem{
            margin-bottom:5px;
        }
        .fitem label{
            display:inline-block;
            width:80px;
        }
    </style>

    <script type="text/javascript">
        var url;
        function newUser(){
            $('#dlg').dialog('open').dialog('setTitle','New User');
            $('#fm').form('clear');
            url = 'add_stu.do';
        }
        function editUser(){
            var row = $('#dg').datagrid('getSelected');
            if (row){
                $('#dlg').dialog('open').dialog('setTitle','Edit User');
                $('#fm').form('load',row);
                url = 'edit_stu.do?id='+row.id;
            }
        }
        function saveUser(){
            $('#fm').form('submit',{
                url: url,
                onSubmit: function(){
                    return $(this).form('validate');
                },
                success: function(result){
                    var result = eval('('+result+')');
                    if (result.success){
                        $('#dlg').dialog('close');        // close the dialog
                        $('#dg').datagrid('reload');    // reload the user data
                        $.messager.show({
                            title: 'Message',
                            msg: '添加成功'
                        });
                    } else {
                        $.messager.show({
                            title: 'Error',
                            msg: result.msg
                        });
                    }
                }
            });
        }
        function removeUser(){
            var row = $('#dg').datagrid('getSelected');
            if (row){
                $.messager.confirm('Confirm','Are you sure you want to remove this user?',function(r){
                    if (r){
                        $.post('remove_stu.do',{id:row.id},function(result){
                            if (result.success){
                                $('#dg').datagrid('reload');    // reload the user data
                                $.messager.show({
                                    title: 'Message',
                                    msg: '添加成功'
                                });
                            } else {
                                $.messager.show({    // show error message
                                    title: 'Error',
                                    msg: result.msg
                                });
                            }
                        },'json');
                    }
                });
            }
        }
    </script>
</head>
<body>
    <h2>Basic CRUD Application</h2>
    <div class="demo-info" style="margin-bottom:10px">
        <div class="demo-tip icon-tip">&nbsp;</div>
        <div>Click the buttons on datagrid toolbar to do crud actions.</div>
    </div>
    
    <table id="dg" title="My Users" class="easyui-datagrid" style="width:700px;height:250px"
            url="get_stu.do"
            toolbar="#toolbar" pagination="true"
            rownumbers="true" fitColumns="true" singleSelect="true">
        <thead>
            <tr>
                <th field="name" width="50">Name</th>
            </tr>
        </thead>
    </table>
    <div id="toolbar">
        <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newUser()">New User</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editUser()">Edit User</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="removeUser()">Remove User</a>
    </div>
    
    <div id="dlg" class="easyui-dialog" style="width:400px;height:280px;padding:10px 20px"
            closed="true" buttons="#dlg-buttons">
        <div class="ftitle">User Information</div>
        <form id="fm" method="post" novalidate>
            <div class="fitem">
                <label>Name:</label>
                <input name="name" class="easyui-validatebox" required="true">
            </div>
        </form>
    </div>
    <div id="dlg-buttons">
        <a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveUser()">Save</a>
        <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')">Cancel</a>
    </div>
</body>
</html>

 

Action:

View Code
package com.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.hibernate.Session;

import com.entity.Student;
import com.opensymphony.xwork2.ActionSupport;

import dao.HibernateSessionFactory;

public class StudentAction extends ActionSupport implements ServletRequestAware{
    private Session session = HibernateSessionFactory.getSession();
    private HttpServletRequest request ;
    @Override
    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
    }
    private int id;
    /**
     * 分页查找
     * @return
     * @throws IOException
     */
    public String get_stu() throws IOException{
        //当前页数
        String page = request.getParameter("page")==null?"1":request.getParameter("page");
        //显示条数
        String rows = request.getParameter("rows")==null?"10":request.getParameter("rows");
        //从第几条开始
        int offset = (Integer.parseInt(page)-1)*Integer.parseInt(rows);
        //总数量
        Object rs = session.createQuery("select count(*) from Student").uniqueResult();
        //分页查询,从第几条(offset)开始,显示多少(rows)条
        List<Student> uList = session.createCriteria(Student.class).setFirstResult(offset).setMaxResults(Integer.parseInt(rows)).list();
        //json格式返回总条数以及查询到的集合
        JSONObject json = JSONObject.fromObject(new Object()).element("total", Integer.parseInt(rs.toString())).element("rows", uList);
        ServletActionContext.getResponse().getWriter().write(json.toString());
        return null;
    }
    
    /**
     * 添加
     * @return
     * @throws IOException
     */
    public String add_stu() throws IOException{
        session.beginTransaction();
        Student stu = new Student(request.getParameter("name"));
        session.save(stu);
        session.beginTransaction().commit();
        JSONObject json = JSONObject.fromObject(new Object()).element("success", true);
        ServletActionContext.getResponse().getWriter().write(json.toString());
        return null;
    }
    /**
     * 修改
     * @return
     * @throws IOException
     */
    public String edit_stu() throws IOException{
        session.beginTransaction();
        Student stu = (Student) session.get(Student.class, id);
        stu.setName(request.getParameter("name"));
        session.update(stu);
        session.beginTransaction().commit();
        JSONObject json = JSONObject.fromObject(new Object()).element("success", true);
        ServletActionContext.getResponse().getWriter().write(json.toString());
        return null;
    }
    /**
     * 删除
     * @return
     * @throws IOException
     */
    public String remove_stu() throws IOException{
        session.beginTransaction();
        session.delete(session.get(Student.class, id));
        session.beginTransaction().commit();
        JSONObject json = JSONObject.fromObject(new Object()).element("success", true);
        ServletActionContext.getResponse().getWriter().write(json.toString());
        return null;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

}

Struts:

View Code
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
    <constant name="struts.action.extension" value="do" />  
<package name="users_default" extends="struts-default">
        
        <action name="get_users" class="com.action.UsersAction" method="get_users">
        </action>
        
        <action name="get_stu" class="com.action.StudentAction" method="get_stu">
        </action>
                <action name="remove_stu" class="com.action.StudentAction" method="remove_stu">
        </action>
                <action name="edit_stu" class="com.action.StudentAction" method="edit_stu">
        </action>
                <action name="add_stu" class="com.action.StudentAction" method="add_stu">
        </action>
    </package>
</struts>    

HTML验证邮箱:

View Code
<div class="fitem">
                <label>Email:</label>
                <input name="email" class="easyui-validatebox" validType="email">
            </div>

 

表结构:id name;

数据库:MySQL;

 

数据列可以增加减少,数据库可以更变.

缺点是初学者只能按照他给的参数进行开发.

例如返回JSON字符串,名称要一致.

这就像进别人公司,要遵循别人的规章制度.

除非你有能力去做到更变在规章制度,就可以自己更变扩展该插件.

 

 

 

 

直接在表格上实现增删改

View Code
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <meta name="keywords" content="jquery,ui,easy,easyui,web">

    <meta name="description" content="easyui help you build your web page easily!">

    <title>Build CRUD DataGrid with jQuery EasyUI - jQuery EasyUI Demo</title>

    <link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/default/easyui.css">

    <link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/icon.css">

    <link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/demo/demo.css">

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>

    <script type="text/javascript" src="http://www.jeasyui.com/easyui/jquery.easyui.min.js"></script>

    <script type="text/javascript" src="http://www.jeasyui.com/easyui/jquery.edatagrid.js"></script>

    <script type="text/javascript">

        $(function(){

            $('#dg').edatagrid({

                url: 'get_user.do',

                saveUrl: 'add_user.do',

                updateUrl: 'edit_user.do',

                destroyUrl: 'remove_user.do'

            });

        });

    </script>

</head>

<body>

    <h2>CRUD DataGrid</h2>

    <div class="demo-info" style="margin-bottom:10px">

        <div class="demo-tip icon-tip">&nbsp;</div>

        <div>Double click the row to begin editing.</div>

    </div>

    

    <table id="dg" title="My Users" style="width:700px;height:250px"

            toolbar="#toolbar" pagination="true"

            rownumbers="true" fitColumns="true" singleSelect="true">

        <thead>

            <tr>

                <th field="firstname" width="50" editor="{type:'validatebox',options:{required:true}}">First Name</th>

                <th field="lastname" width="50" editor="{type:'validatebox',options:{required:true}}">Last Name</th>

                <th field="phone" width="50" editor="text">Phone</th>

                <th field="email" width="50" editor="{type:'validatebox',options:{validType:'email'}}">Email</th>

            </tr>

        </thead>

    </table>

    <div id="toolbar">

        <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="javascript:$('#dg').edatagrid('addRow')">New</a>

        <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="javascript:$('#dg').edatagrid('destroyRow')">Destroy</a>

        <a href="#" class="easyui-linkbutton" iconCls="icon-save" plain="true" onclick="javascript:$('#dg').edatagrid('saveRow')">Save</a>

        <a href="#" class="easyui-linkbutton" iconCls="icon-undo" plain="true" onclick="javascript:$('#dg').edatagrid('cancelRow')">Cancel</a>

    </div>

    

</body>

</html>
posted @ 2012-05-26 17:29  时生  阅读(5711)  评论(1编辑  收藏  举报