easyui-datagrid 增删改查 ,支持对行进行双击编辑修改, 从页面到后台的代码,绿色部分为转为为json字符串
html 页面代码
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>operateDataGrid.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../css/themes/default/easyui.css" type="text/css"></link>
<link rel="stylesheet" href="../css/themes/icon.css" type="text/css"></link>
<script type="text/javascript" src="../js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="../js/jquery.easyui.min.js"></script>
<!-- 引入中文资源 -->
<script type="text/javascript" src="../js/easyui-lang-zh_CN.js"></script>
<script type="text/javascript" src="operateDataGrid.js"></script>
<script type="text/javascript">
//设置datagrid自适应
$(window).resize(function () {
$('#dataGrid').datagrid('resize')
});
</script>
</head>
<body>
<div width="100%">
<table id="dataGrid"></table>
</div>
</body>
</html>
operateDataGrid.js 代码
var dataGridOper;
//定义右键点击时选择的行
var rightIndex = -1;
$.extend($.fn.datagrid.methods, {
//增加时有编辑框
//第一个参数组件本身,第二个参数要传递的参数
addEditor: function(jq, param){
if (param instanceof Array) {
$.each(param, function(index, item){
var e = $(jq).datagrid('getColumnOption', item.field);
e.editor = item.editor;
});
}
else {
var e = $(jq).datagrid('getColumnOption', param.field)
e.editor = param.editor;
}
},
//修改时没编辑框
//编辑时使用可以跳过指定的列编辑,对某些列不需要编辑
// 如 datagrid('removeEditor','password'),不让编辑密码
removeEditor: function(jq, param){
if (param instanceof Array) {
$.each(param, function(index, item){
var e = $(jq).datagrid('getColumnOption', item);
e.editor = {};
});
}
else {
var e = $(jq).datagrid('getColumnOption', param)
e.editor = {};
}
}
})
/**
* 扩展datagrid的列editor
* @param {Object} container
* @param {Object} options
*/
$.extend($.fn.datagrid.defaults.editors, {
//扩展datatimebox
datetimebox: {
init: function(container, options){
//初始化datatimebox
var input = $('<input />').appendTo(container);
//不可输入
options.editable = false;
input.datetimebox(options);
return input;
},
getValue: function(target){
return $(target).datatimebox('getValue');
},
setValue: function(target, value){
$(target).datatimebox('setValue', value);
},
resize: function(target, width){
$(target).datatimebox('resize', width);
},
destroy: function(target){
//销毁datetimebox弹出的panel
$(target).datatimebox('destroy');
}
},
//单选框
radioButton: {
init: function(container, options){
//初始化datatimebox
var input = $('<input type="radio" name="radio" value="M" />男 <input type="radio" name="radio" value="F" />女 ').appendTo(container);
return input;
},
getValue: function(target){
alert($(target).val())
return $(target).val();
},
setValue: function(target, value){
$(target).val(value);
},
resize: function(target, width){
}
}
});
//js获取项目根路径,如: http://localhost:8088/jquery
function getRootPath(){
//获取当前网址,如: http://localhost:8088/jquery/easyui/login.jsp
var curWwwPath = window.document.location.href;
//获取主机地址之后的目录,如: jquery/easyui/login.jsp
var pathName = window.document.location.pathname;
var pos = curWwwPath.indexOf(pathName);
//获取主机地址,如: http://localhost:8088
var localhostPaht = curWwwPath.substring(0, pos);
//获取带"/"的项目名,如:/jquery
var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
return (localhostPaht + projectName);
}
$(function(){
operateDataGrid();
});
var operateDataGrid = function(){
//用于存放操作记录
var operator = "";
//存放编辑的行号
var editorRow = -1;
dataGridOper = $('#dataGrid').datagrid({
url: getRootPath() + '/operateDataGrid?operator=selectData',
method: 'post',
title: '用户信息',
fitColumns: true,
width: '100%',
height: 335,
loadMsg: 'loading',
striped: true,
//idField: 'oid',
rownumbers: true,
//设置默认排序字段
sortName: 'username',
columns: [[{
field: 'oid',
title: '编号',
width: 100,
align: 'center',
//设置可以排序,则不显示此列
checkbox: true
}, {
field: 'username',
title: '姓名',
width: 100,
align: 'center',
//设置可以排序
sortable: true,
editor: {
//string,object string 时指编辑类型,当 object 是options:对象,编辑类型对应的编辑器选项
type: 'validatebox',
options: {
required: true
}
}
}, {
field: 'gender',
title: '性别',
width: 100,
align: 'center',
sortable: true,
editor: {
//string,object
type: 'validatebox'
},
formatter: function(value, rowData, rowIndex){
return (($.trim(value) == "F") ? "女" : "男");
}
}, {
field: 'phonenum',
title: '电话',
width: 100,
align: 'center',
sortable: true,
editor: {
//string,object
//type: 'datetimebox',
type: 'text',
options: {
required: true
}
}
}]],
pagination: true,
//工具栏,每个都是一个LinkButton
toolbar: [{
id: 'idAdd',
text: '增加',
iconCls: 'icon-add',
plain: 'true',
//按钮事件
handler: function(){
//控制一次只能添加一行
if (editorRow == -1) {
//增加时可以对用户名进行编辑
dataGridOper.datagrid('addEditor', {
field: 'username',
editor: {
//string,object string 时指编辑类型,当 object 是options:对象,编辑类型对应的编辑器选项
type: 'validatebox',
options: {
required: true
}
}
});
operator = "insertData";
//在第一行增加
dataGridOper.datagrid('insertRow', {
//index:插入进去的行的索引,如果没有定义,就追加此新行,row:行的数据
index: 0,
row: {
//初始化的数据
username: '请输入姓名',
gender: '请填写性别',
phonenum: '请填写电话'
}
});
//队列进行编辑时必须在columns中列设置editor属性
//开始第一行进行编辑,参数index 索引
dataGridOper.datagrid('beginEdit', 0);
editorRow = 0;
}
else {
$.messager.alert('提示', '请先保存正在修改的数据', 'warning');
//dataGridOper.datagrid('endEdit', editorRow);
}
}
}, '-', {
id: 'idDelete',
text: '删除',
disabled: true,
iconCls: 'icon-remove',
//按钮事件
handler: function(){
//获取选中的行数
var rows = dataGridOper.datagrid('getSelections');
if (rows.length > 0) {
//存放选中行的id
var ids = [];
for (var i = 0; i < rows.length; i++) {
ids.push(rows[i].oid);
}
//调用后台删除
$.ajax({
type: "POST",
url: getRootPath() + '/operateDataGrid?operator=delData',
data: 'ids=' + ids.join(','),
dataType: 'text',
success: function(msg){
if (msg == "success") {
//title, msg, icon, fn
$.messager.alert('系统提示', '删除成功', 'info', function(btn){
//回调函数
dataGridOper.datagrid('load');
});
}
else
if (msg == 'noData') {
$.messager.alert('系统提示', '请选择要删除的数据', 'warning')
}
else {
$.messager.alert('系统提示', '删除失败', 'error')
}
},
error: function(XMLHttpRequest, textStatus, errorThrown){
$.messager.alert('系统提示', '删除失败:' + textStatus, 'info')
}
})
}
else {
//title, msg, icon, fn
$.messager.alert('系统提示', '请选择索要操作的数据', 'info');
}
}
}, '-', {
id: 'idEdit',
text: '修改',
iconCls: 'icon-edit',
disabled: true,
handler: function(){
//控制一次只能编辑一行
var rows2 = dataGridOper.datagrid('getSelections');
//console.info(rows2[0]);
//一次只能编辑一行
if (rows2.length == 1) {
//判断是否有其他行正在编辑
if (editorRow == -1) {
//不让编辑用户名
//dataGridOper.datagrid('removeEditor', ['username','']); 传多个对象
dataGridOper.datagrid('removeEditor', 'username');
//返回指定行的索引,row 参数可以是一个行记录或者一个 id 字段的值
var index1 = dataGridOper.datagrid('getRowIndex', rows2[0]);
operator = "updateData";
//在第一行增加
//队列进行编辑时必须在columns中列设置editor属性
//开始对一行进行编辑,参数index 索引
dataGridOper.datagrid('beginEdit', index1);
editorRow = index1;
}
else {
$.messager.confirm('提示', '是否保存正在修改的数据', function(btn2){
//点击确定则保存,否则取消
if (btn2) {
dataGridOper.datagrid('endEdit', editorRow);
//设置当前无正在编辑的行
editorRow = -1;
}
});
}
}
else {
$.messager.alert('提示', '一次只能对一行进行编辑', 'warning');
}
}
}, '-', {
id: 'idSave',
text: '保存',
iconCls: 'icon-save',
//disabled: true,
handler: function(){
//结束对第一行进行编辑,参数index 索引
if (editorRow != -1) {
dataGridOper.datagrid('endEdit', editorRow);
}
}
}, '-', {
id: 'idCancle',
text: '取消编辑',
iconCls: 'icon-undo',
//disabled: true,
handler: function(){
//获取总数
var paper = dataGridOper.datagrid('getPager');
var total = paper.pagination('options').total;
//回滚自从创建以来或最后一次调用acceptChanges以来所有更改的数据
dataGridOper.datagrid('rejectChanges');
//重新设置总数
paper.pagination({total:total});
editorRow = -1;
//取消选中时,则删除,修改按钮不可用
$('#idDelete').linkbutton('disable');
$('#idEdit').linkbutton('disable');
}
}, '-'],
onSelect: function(rowIndex, rowData){
//选中时,则删除,修改按钮可用
$('#idDelete').linkbutton('enable');
$('#idEdit').linkbutton('enable');
},
onSelectAll: function(rows){
//选中时,则删除,修改按钮可用
$('#idDelete').linkbutton('enable');
$('#idEdit').linkbutton('enable');
},
onUnselect: function(rowIndex, rowData){
//当取消全部选中时则按钮不可用
var rows = dataGridOper.datagrid('getSelections');
if (rows.length == 0) {
//取消选中时,则删除,修改按钮不可用
$('#idDelete').linkbutton('disable');
$('#idEdit').linkbutton('disable');
}
},
onUnselectAll: function(rows){
//取消选中时,则删除,修改按钮不可用
$('#idDelete').linkbutton('disable');
$('#idEdit').linkbutton('disable');
},
onAfterEdit: function(rowIndex, rowData, changes){
//获取最后一次提交以来更改的行,type 参数表示更改的行的类型,可能的值是:inserted、deleted、updated,等等。
//dataGridOper.datagrid('getChanges', 'inserted');//用于判断是增删改的操作
//当用户完成编辑一行时触发,参数包括rowIndex:编辑行的索引,从 0 开始
//rowData:编辑行对应的记录 changes:更改的字段/值对
var urlData = "";
if (operator == "insertData") {
urlData = "username=" + rowData.username + "&gender=" + rowData.gender + "&phone=" + rowData.phonenum;
}
else {
urlData = "id=" + rowData.oid + "&gender=" + rowData.gender + "&phone=" + rowData.phonenum;
}
$.ajax({
type: "POST",
url: getRootPath() + '/operateDataGrid?operator=' + operator,
data: urlData,
dataType: 'text',
success: function(msgResult){
//console.info(msgResult);
if (msgResult == "success") {
//提交自从被加载以来或最后一次调用acceptChanges以来所有更改的数据,
//保持该数据的状态,否则点击取消编辑,将会回到修改前的数据,相当于提交事务
dataGridOper.datagrid('acceptChanges');
//title, msg, icon, fn
$.messager.alert('系统提示', '保存成功', 'info', function(btn){
//回调函数
dataGridOper.datagrid('load');
});
}
else {
$.messager.alert('系统提示', '保存失败', 'error');
//回滚
dataGridOper.datagrid('rejectChanges');
}
editorRow = -1;
},
error: function(XMLHttpRequest, textStatus, errorThrown){
$.messager.alert('系统提示', '保存失败:' + textStatus, 'info')
}
});
},
onDblClickRow: function(rowIndex, rowData){
//当用户双击一行时触发,参数包括,rowIndex:被双击行的索引,从 0 开始,rowData:被双击行对应的记录
//双击行时进行编辑该行
//控制一次只能编辑一行
if (editorRow == -1) {
operator = "updateData";
//不让编辑用户名
dataGridOper.datagrid('removeEditor', 'username');
//在第一行增加
//队列进行编辑时必须在columns中列设置editor属性
//开始对一行进行编辑,参数index 索引
dataGridOper.datagrid('beginEdit', rowIndex);
editorRow = rowIndex;
}
else {
$.messager.confirm('提示', '是否保存正在修改的数据', function(btn2){
//点击确定则保存,否则取消
if (btn2) {
dataGridOper.datagrid('endEdit', editorRow);
//设置当前无正在编辑的行
editorRow = -1;
}
});
}
},
onClickRow: function(rowIndex, rowData){
//当用户点击一行时触发,参数包括: rowIndex:被点击行的索引,从0开始 rowData:被点击行对应的记录
//判断是否有正在修改的数据
if (editorRow != -1) {
$.messager.confirm('提示', '是否保存正在修改的数据', function(btn2){
//点击确定则保存,否则取消
if (btn2) {
dataGridOper.datagrid('endEdit', editorRow);
//设置当前无正在编辑的行
editorRow = -1;
}
});
}
},
//当右键点击行时触发
onRowContextMenu: function(e, rowIndex, rowData){
//console.info(e);
//阻止浏览器默认的右键事件
e.preventDefault();
rightIndex = rowIndex;
//添加菜单
$('#editMenu').menu('show', {
left: e.pageX,
top: e.pageY
});
}
});
}
/**
* 右键增加
*/
function addRow(){
$('#idAdd').data().linkbutton.options.handler();
}
/**
* 右键修改
*/
function editRow(){
//取消选中当前页所有的行
dataGridOper.datagrid('unselectAll');
dataGridOper.datagrid('selectRow', rightIndex);
$('#idEdit').data().linkbutton.options.handler();
}
/**
* 右键删除
*/
function delRow(){
//取消选中当前页所有的行
dataGridOper.datagrid('unselectAll');
dataGridOper.datagrid('selectRow', rightIndex);
$('#idDelete').data().linkbutton.options.handler();
}
web.xml 代码
<servlet>
<servlet-name>OperateDataGridServlet</servlet-name>
<servlet-class>com.OperateDataGridServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>OperateDataGridServlet</servlet-name>
<url-pattern>/operateDataGrid</url-pattern>
</servlet-mapping>
java后台 代码
servlet 代码
package com;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class OperateDataGridServlet extends HttpServlet
{
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
String operator = request.getParameter("operator");
if (null != operator)
{
DBBaseDao dao = new DBBaseDao();
if ("selectData".equals(operator))
{
Map map = new HashMap();
List list = new ArrayList();
try
{
String sqlCount = "select count(1) from userinfo u where u.enable_flag='T'";
ResultSet rss = dao.querySql(sqlCount);
int count = 0;
while (rss.next())
{
count = Integer.valueOf(rss.getString("count(1)"));
}
if (count > 0)
{
// 获取分页条件
String pageStr = request.getParameter("page");
String rowStr = request.getParameter("rows");
// 获取排序字段和类型
String sort = request.getParameter("sort");
String order = request.getParameter("order");
int page = 0;
int row = 0;
if (pageStr != "" && pageStr != null)
{
page = Integer.parseInt(pageStr);
}
if (rowStr != "" && rowStr != null)
{
row = Integer.parseInt(rowStr);
}
int start = (page - 1) * row;
int end = page * row;
String sqlStr = "select * from (select a.*, rownum m from "
+ "(select u.oid,u.username,u.gender,u.phonenum from userinfo u"
+ " where u.enable_flag='T' order by "
+ sort
+ " "
+ order
+ ") a where rownum<="
+ end
+ " ) where m>"
+ start;
ResultSet rs = dao.querySql(sqlStr);
UserInfo user = null;
while (rs.next())
{
user = new UserInfo();
user.setOid(rs.getString("oid"));
user.setUsername(rs.getString("username"));
user.setGender(rs.getString("gender"));
user.setPhonenum(rs.getString("phonenum"));
list.add(user);
}
}
// 设置总数
map.put("total", count);
// 设置行数据
map.put("rows", list);
}
catch (SQLException e)
{
e.printStackTrace();
}
// response.getWriter().write(JsonUtil.list2json(list));
response.getWriter().write( JsonUtil.map2json(map));
}
else if ("delData".equals(operator))
{
String ids = request.getParameter("ids");
if(ids==null || "".equals(ids)){
response.getWriter().print("noData");
}else{
String sql ="update userinfo u set u.enable_flag='T' where oid in("+ids+")";
int num = dao.updateSql(sql);
dao.closeAll();
if(num>0){
response.getWriter().print("success");
}else{
response.getWriter().print("failer");
}
}
}
else if ("insertData".equals(operator))
{
String username = request.getParameter("username");
String gender = request.getParameter("gender");
String phone = request.getParameter("phone");
String sql ="insert into userinfo(oid,enable_flag,username,gender,phonenum) values (userinfo_S.NEXTVAL,'T','"+username+"','"+gender+"','"+phone+"')";
int num = dao.updateSql(sql);
dao.closeAll();
if(num>0){
response.getWriter().print("success");
}else{
response.getWriter().print("failer");
}
}
else if ("updateData".equals(operator))
{
String id = request.getParameter("id");
String gender = request.getParameter("gender");
String phone = request.getParameter("phone");
String sql ="update userinfo u set u.gender='"+gender+"',phonenum='"+phone+"' where oid in("+id+")";
int num = dao.updateSql(sql);
dao.closeAll();
if(num>0){
response.getWriter().print("success");
}else{
response.getWriter().print("failer");
}
}
}
}
}
dao 层代码
package com;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 操作数据库
*
* @author kou
*/
public class DBBaseDao
{
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
// public Connection getConnection()
// {
// try
// {
// Class.forName("oracle.jdbc.driver.OracleDriver");
// conn = DriverManager.getConnection(
// "jdbc:oracle:thin:@127.0.0.1:1521:user", "admin",
// "admin");
// }
// catch (Exception e)
// {
// e.printStackTrace();
// }
//
// return conn;
// }
static
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch (Exception e)
{
e.printStackTrace();
}
}
public DBBaseDao()
{
try
{
conn = DriverManager.getConnection(
"jdbc:oracle:thin:@127.0.0.1:1521:user", "admin",
"admin");
}
catch (SQLException e)
{
e.printStackTrace();
}
}
/**
* 查询结果集
*
* @param sql
* @return
*/
public ResultSet querySql(String sql)
{
// conn = getConnection();
try
{
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
}
catch (SQLException e)
{
e.printStackTrace();
}
return rs;
}
/**
* 更新
*
* @param sql
* @return
*/
public int updateSql(String sql)
{
// conn = getConnection();
int count = 0;
try
{
pst = conn.prepareStatement(sql);
count = pst.executeUpdate();
}
catch (SQLException e)
{
e.printStackTrace();
}
return count;
}
/**
* 关闭所有连接
*/
public void closeAll()
{
try
{
if (conn != null || !conn.isClosed())
{
conn.close();
}
if (pst != null)
{
pst.close();
}
if (rs != null)
{
rs.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
实体类
package com;
public class UserInfo
{
private String oid;
private String username;
private String gender;
private String phonenum;
public String getOid()
{
return oid;
}
public void setOid(String oid)
{
this.oid = oid;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getGender()
{
return gender;
}
public void setGender(String gender)
{
this.gender = gender;
}
public String getPhonenum()
{
return phonenum;
}
public void setPhonenum(String phonenum)
{
this.phonenum = phonenum;
}
}