easyui实现动态数据的增删改查

前言

因为前面博客系统性的写了相关的代码和注意实现这里就不重复了,照样还是用自己写的mvc框架来配合easyui实现增删改查。

思路

其实主要注意两点:

  1. 缓存的问题,如果修改完js文件后不清空浏览器的缓存或者eclipse的缓存的话,你运行时候它还是会停留在你修改前的状态中的,解决方案Shift+Ctrl+Delete清除浏览器的历史记录,eclipse中找到 project--->clean
  2. 一定要细心细心细心,不要一下少个逗号或者单词写错里面没有快捷键的。

好了还是基于官方文档,首先我们需要了解,修改和增加是不需要进行跳转界面的,模态框即可解决,模态框是包含表单在内的,表单的name值需要和实体类对应,不能错一个单词,不然效果出不来,利用jquery把需要用到的标签进行事件绑定,在事件里面利用文档提供的方法、事件、属性配合mvc框架与后台交互进行数据渲染。

流程

在这里插入图片描述

代码实现

这是我准备的依赖和工具类
在这里插入图片描述
这是项目的依赖
在这里插入图片描述

1.前端代码

1.1addBook.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!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">
<!-- 全局样式 -->
<link rel="stylesheet" type="text/css"
	href="${pageContext.request.contextPath }/static/js/jquery-easyui-1.5.1/themes/default/easyui.css">
<!-- 定义图标 -->
<link rel="stylesheet" type="text/css"
	href="${pageContext.request.contextPath }/static/js/jquery-easyui-1.5.1/themes/default/easyui.css">
<script type="text/javascript"
	src="${pageContext.request.contextPath }/static/js/jquery-easyui-1.5.1/jquery.min.js"></script>
<!-- 主键库源码的JS文件 -->
<script type="text/javascript"
	src="${pageContext.request.contextPath }/static/js/jquery-easyui-1.5.1/jquery.easyui.min.js"></script>

<script type="text/javascript"
	src="${pageContext.request.contextPath }/bg/addBook.js"></script>

<title>新增界面</title>
</head>
<body>
	<input type="hidden" id="ctx"
		value="${pageContext.request.contextPath }">
	<div id="tb">
		名字: <input class="easyui-textbox" id="name" name="name"
			style="width: 20%; padding-left: 10px" data-option=""> <a
			id="btn-serch" href="#" class="easyui-linkbutton"
			data-options="iconCls:'icon-edit',plain:true">搜索</a> <a id="btn-add"
			class="easyui-linkbutton"
			data-options="iconCls:'icon-help',plain:true">新增</a>
	</div>
	<div id="dd" class="easyui-dialog" title="新型编辑窗体"
		style="width: 600px; height: 600px;"
		data-options="iconCls:'icon-save',resizable:true,modal:true,closed:true,buttons:'#fbtns'">
		<form id="ff" method="post">
			<input type="text" name="id" />
			<div>
				<label for="name">书籍名称:</label> <input class="easyui-validatebox"
					type="text" name="name" data-options="required:true" />
			</div>
			<div>
				<label for="author">书籍类别:</label> <input class="easyui-validatebox"
					type="text" name="author" data-options="required:true" />
			</div>
			<div>
				<label for="price">价格:</label> <input class="easyui-validatebox"
					type="text" name="price" data-options="required:true" />
			</div>
			<div>
				<label for="image">图片地址:</label> <input class="easyui-validatebox"
					type="text" name="image" data-options="required:true" />
			</div>
			<div>
				<label for="publishing">出版社:</label> <input
					class="easyui-validatebox" type="text" name="publishing"
					data-options="required:true" />
			</div>
			<div>
				<label for="description">描述:</label> <input
					class="easyui-validatebox" type="text" name="description"
					data-options="required:true" />
			</div>
			<div>
				<label for="state">物流状态:</label> <input class="easyui-validatebox"
					type="text" name="state" data-options="required:true" />
			</div>
			<div>
				<label for="deployTime">发布时间:</label> <input
					class="easyui-validatebox" type="text" name="deployTime"
					data-options="required:true" />
			</div>
			<div>
				<label for="sales">数量:</label> <input class="easyui-validatebox"
					type="text" name="sales" data-options="required:true" />
			</div>
		</form>

	</div>

	<div id="fbtns">
		<a id="btn-save" href="#" class="easyui-linkbutton"
			data-options="iconCls:'icon-edit',plain:true">保存</a> <a
			id="btn-cancel" class="easyui-linkbutton"
			data-options="iconCls:'icon-help',plain:true">取消</a>
	</div>

	<table id="dg"></table>
</body>
</html>
1.2addBook.js

这是前端和后台交互的核心逻辑,为了方便大家理解我注释写的比较多。

$(function(){
	var src = $("#ctx").val();
	$('#dg').datagrid({   
	    url:src+'/book.action?methodName=datagrid', 
//	         要进行分页
	   pagination:true,
//	        每次只能选中一行
	   singleSelect:true,
	    toolbar:'#tb',
//	             加载想要的列
	    columns:[[    
	        {field:'id',title:'id',width:100},    
	        {field:'name',title:'名称',width:100},   
	        {field:'pinyin',title:'拼音',width:100},  
	        {field:'cid',title:'副id',width:100},  
	        {field:'author',title:'作者',width:100},  
	        {field:'price',title:'价格',width:100}, 
	        {field:'image',title:'路径',width:100}, 
	        {field:'publishing',title:'出版社',width:100}, 
	        {field:'description',title:'描述',width:100}, 
	        {field:'state',title:'更新',width:100}, 
	        {field:'deployTime',title:'时间',width:100}, 
	        {field:'sales',title:'数量',width:100}, 
//	                         绑定操作事件
	        {field:'xxxx',title:'操作',width:100,formatter: function(value,row,index){
				return '<a href="javascript:void(0)" οnclick="edit()">修改</a>&nbsp;&nbsp;<a href="javascript:void(0)" οnclick="del()">删除</a>'
			}
}    
	    ]]    
	}); 
//	点击搜索按钮完成按名字进行书籍查询
	$("#btn-serch").click(function(){
		$('#dg').datagrid('load', {    
		    name: $("#name").val() 
		});  
	})	
	
	//给新增按钮绑定点击事件
	$("#btn-add").click(function(){
		//需要打开dialog窗体,可以去查看改组件的方法api
		$('#dd').dialog('open');  
	});
	
	//增加修改合二为
	$("#btn-save").click(function(){
//		加载表单中的提交
		$('#ff').form('submit',{   
			 url:src+'/book.action?methodName=save',  
//			 成功函数返回的值
		    success:function(data){  
//				将括号内的表达式('data')转化为对象
		    	data=eval('('+data+')');
//		    	判断结果码是否正常
		       if(data.code == 200){
//		    	   提示操作成功
		    	   alert(data.msg)
//		    	         清空态框
		    	   $('#ff').form('clear');
//		    	          关闭模态框
		    	   $('#dd').dialog('close');
//		    	          刷新数据
		    	   $('#dg').datagrid('reload'); 
		       }
		    }    
		}); 
	})
	
	//关闭
	$("#btn-cancel").click(function(){
//        关闭模态框
 	   $('#dd').dialog('close');
	})
})

//修改
function  edit(){
//	alert(1);
//	做数据回显就是将选中的datagrid行值进行回填到from表单、
	
//	获取到数据表格中选中的行对象
	 var row =$('#dg').datagrid('getSelected');
//	 如果行对象存在就加载到模态框中显示
	 if(row){
		 $('#ff').form('load',row); 
	 }
//	   显示模态框
	 $('#dd').dialog('open');
}
//删除
function del(){
//	从获取到行对象开始
	var row =$('#dg').datagrid('getSelected');
//	不为空的话就进行下一步处理
	 if(row){
//			加载ajax进行局部刷新
		$.ajax({
//          加载资源
			url:ctx+'/book.action?methodName=del&&id='+row.id,
//			得到成功函数返回的值
			success:function(data){ 
//				将括号内的表达式('data')转化为对象
				data=eval('('+data+')');
		       if(data.code == 200){
		    	   alert(data.msg)
//		    	          刷新数据
		    	   $('#dg').datagrid('reload'); 
		       }
		    } 
		});
	 }
}

2.后台代码

2.1.BookDao
package com.liyingdong.dao;

import java.sql.SQLException;
import java.util.List;
import com.liyingdong.entity.Book;
import com.liyingdong.util.BaseDao;
import com.liyingdong.util.PageBean;
import com.liyingdong.util.PinYinUtil;
import com.liyingdong.util.StringUtils;

public class BookDao extends BaseDao<Book> {
	// 通用分页
	public List<Book> list(Book book, PageBean pageBean) throws Exception {
		String name = book.getName();
		String sql = "select * from t_easyui_book where true ";
		if (StringUtils.isNotBlank(name)) {
			sql += " and name like '%" + name + "%' ";
		}
		return super.executeQuery(sql, Book.class, pageBean);
	}

	// 增加
	public int add(Book book) throws NoSuchFieldException, SecurityException, IllegalArgumentException,
			IllegalAccessException, SQLException {
		book.setPinyin(PinYinUtil.getAllPingYin(book.getName()));
		String sql = "insert into t_easyui_book  values(null,?,?,?,?,?,?,?,?,?,?,?)";
		return super.executeUpdate(sql, book, new String[] { "name", "pinyin", "cid", "author", "price", "image",
				"publishing", "description", "state", "deployTime", "sales", });

	}

	// 删除
	public int del(Book book) throws NoSuchFieldException, SecurityException, IllegalArgumentException,
			IllegalAccessException, SQLException {
		String sql = "delete from t_easyui_book where id=?";
		return super.executeUpdate(sql, book, new String[] { "id" });
	}

	// 修改
	public int edit(Book book) throws NoSuchFieldException, SecurityException, IllegalArgumentException,
			IllegalAccessException, SQLException {
		book.setPinyin(PinYinUtil.getAllPingYin(book.getName()));
		String sql = "update  t_easyui_book  set  name=?,pinyin=?,cid=?,author=?,price=?,image=?,publishing=?,description=?,state=?,deployTime=?,sales=? where id=?";
		return super.executeUpdate(sql, book, new String[] { "name", "pinyin", "cid", "author", "price", "image",
				"publishing", "description", "state", "deployTime", "sales", "id" });

	}

}

2.2.BookAction
package com.liyingdong.web;

import java.sql.SQLException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.liyingdong.dao.BookDao;
import com.liyingdong.entity.Book;
import com.liyingdong.framework.ActionSupport;
import com.liyingdong.framework.ModelDriver;
import com.liyingdong.util.DataGridResult;
import com.liyingdong.util.PageBean;
import com.liyingdong.util.ResponseUtil;
import com.liyingdong.util.Result;

public class BookAction extends ActionSupport implements ModelDriver<Book> {

	private Book book = new Book();
	private BookDao bookDao = new BookDao();

	@Override
	public Book getModel() {
		return book;
	}

	// 查询
	public String datagrid(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		PageBean pageBean = new PageBean();
		pageBean.setRequest(req);
		List<Book> list = bookDao.list(book, pageBean);
		try {
			ResponseUtil.writeJson(resp, DataGridResult.ok(pageBean.getTotal() + "", list));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// 新增修改合起来
	public String save(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		try {
			if (book.getId() != 0) {
				this.bookDao.edit(book);
			} else {
				this.bookDao.add(book);
			}
			ResponseUtil.writeJson(resp, Result.success);
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}
		return null;

	}

	// 删除
	public String del(HttpServletRequest req, HttpServletResponse resp)
			throws InstantiationException, IllegalAccessException, SQLException {
		try {
			this.bookDao.del(book);
			ResponseUtil.writeJson(resp, Result.success);
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}

2.3.Result
package com.liyingdong.util;

public class Result<T> {

	private int code;
	private String msg;
	private T data;
	
	public static Result success=new  Result<>(200,"操作成功");
	
	public static <T> Result ok(T data) {
		return new Result<T>(data);
	}
	public int getCode() {
		return code;
	}
	public void setCode(int code) {
		this.code = code;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	
	public Result(int code, String msg) {
		super();
		this.code = code;
		this.msg = msg;
	}
	
	public T getData() {
		return data;
	}
	public void setData(T data) {
		this.data = data;
	}
	private Result() {
		super();
	}
	private Result(T data) {
		this.data = data;
	}
	
}

运行结果

增加书籍界面。
在这里插入图片描述
修改界面
在这里插入图片描述
删除界面
在这里插入图片描述
操作后效果:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
EasyUI 是一个基于 jQuery 的 UI 库,可以快速地构建出美观的 web 应用程序。对于账户的增删改查功能,可以结合 EasyUI 提供的表格、表单、对话框等组件来实现。 以下是一个简单的账户管理示例: HTML: ```html <!-- 显示账户列表的表格 --> <table id="accountTable" class="easyui-datagrid" style="width:100%;height:400px" url="getAccounts.php" toolbar="#toolbar" pagination="true" rownumbers="true" fitColumns="true" singleSelect="true"> <thead> <tr> <th field="id" width="50" sortable="true">ID</th> <th field="name" width="100" sortable="true">姓名</th> <th field="email" width="150" sortable="true">邮箱</th> <th field="phone" width="100" sortable="true">电话</th> </tr> </thead> </table> <!-- 工具栏,包含新增、编辑、删除按钮 --> <div id="toolbar"> <a href="#" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newAccount()">新增</a> <a href="#" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editAccount()">编辑</a> <a href="#" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="destroyAccount()">删除</a> </div> <!-- 新增/编辑账户的对话框 --> <div id="dlg" class="easyui-dialog" style="width:400px;height:280px;padding:10px 20px" closed="true" buttons="#dlg-buttons"> <div class="ftitle">账户信息</div> <form id="fm" method="post" novalidate> <div class="fitem"> <label>姓名:</label> <input name="name" class="easyui-textbox" required="true"> </div> <div class="fitem"> <label>邮箱:</label> <input name="email" class="easyui-textbox" validType="email"> </div> <div class="fitem"> <label>电话:</label> <input name="phone" class="easyui-textbox"> </div> </form> </div> <!-- 对话框底部的按钮 --> <div id="dlg-buttons"> <a href="#" class="easyui-linkbutton" iconCls="icon-ok" onclick="saveAccount()" style="width:90px">保存</a> <a href="#" class="easyui-linkbutton" iconCls="icon-cancel" onclick="$('#dlg').dialog('close')" style="width:90px">取消</a> </div> ``` JavaScript: ```javascript // 弹出新增账户对话框 function newAccount() { $('#dlg').dialog('open').dialog('setTitle', '新增账户'); $('#fm').form('clear'); } // 弹出编辑账户对话框 function editAccount() { var row = $('#accountTable').datagrid('getSelected'); if (row) { $('#dlg').dialog('open').dialog('setTitle', '编辑账户'); $('#fm').form('load', row); } } // 保存新增/编辑的账户信息 function saveAccount() { $('#fm').form('submit', { url: 'saveAccount.php', onSubmit: function () { return $(this).form('validate'); }, success: function (result) { var result = eval('(' + result + ')'); if (result.success) { $('#dlg').dialog('close'); // 关闭对话框 $('#accountTable').datagrid('reload'); // 刷新表格 } else { $.messager.show({ title: 'Error', msg: result.msg }); } } }); } // 删除选中的账户 function destroyAccount() { var row = $('#accountTable').datagrid('getSelected'); if (row) { $.messager.confirm('Confirm', '确定要删除此账户吗?', function (r) { if (r) { $.post('destroyAccount.php', {id: row.id}, function (result) { if (result.success) { $('#accountTable').datagrid('reload'); // 刷新表格 } else { $.messager.show({ title: 'Error', msg: result.msg }); } }, 'json'); } }); } } ``` PHP: ```php <?php // getAccounts.php:获取账户列表 require_once('dbconfig.php'); $conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME); if (!$conn) { die('连接数据库失败:' . mysqli_connect_error()); } $page = isset($_POST['page']) ? intval($_POST['page']) : 1; $rows = isset($_POST['rows']) ? intval($_POST['rows']) : 10; $offset = ($page - 1) * $rows; $result = array(); $result['total'] = mysqli_num_rows(mysqli_query($conn, "SELECT * FROM accounts")); $sql = "SELECT * FROM accounts LIMIT $offset,$rows"; $rs = mysqli_query($conn, $sql); $rows = array(); while ($row = mysqli_fetch_assoc($rs)) { $rows[] = $row; } $result['rows'] = $rows; mysqli_close($conn); echo json_encode($result); ?> <?php // saveAccount.php:保存新增/编辑的账户信息 require_once('dbconfig.php'); $conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME); if (!$conn) { die('连接数据库失败:' . mysqli_connect_error()); } $id = isset($_POST['id']) ? intval($_POST['id']) : 0; $name = isset($_POST['name']) ? mysqli_real_escape_string($conn, $_POST['name']) : ''; $email = isset($_POST['email']) ? mysqli_real_escape_string($conn, $_POST['email']) : ''; $phone = isset($_POST['phone']) ? mysqli_real_escape_string($conn, $_POST['phone']) : ''; if ($id > 0) { $sql = "UPDATE accounts SET name='$name',email='$email',phone='$phone' WHERE id=$id"; } else { $sql = "INSERT INTO accounts(name,email,phone) VALUES ('$name','$email','$phone')"; } if (mysqli_query($conn, $sql)) { $result = array('success' => true); } else { $result = array('success' => false, 'msg' => '保存失败:' . mysqli_error($conn)); } mysqli_close($conn); echo json_encode($result); ?> <?php // destroyAccount.php:删除指定账户 require_once('dbconfig.php'); $conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME); if (!$conn) { die('连接数据库失败:' . mysqli_connect_error()); } $id = isset($_POST['id']) ? intval($_POST['id']) : 0; if ($id > 0) { $sql = "DELETE FROM accounts WHERE id=$id"; if (mysqli_query($conn, $sql)) { $result = array('success' => true); } else { $result = array('success' => false, 'msg' => '删除失败:' . mysqli_error($conn)); } } else { $result = array('success' => false, 'msg' => '无效的账户ID'); } mysqli_close($conn); echo json_encode($result); ?> ``` 这个示例中,使用了 EasyUI 提供的 `datagrid` 组件来显示账户列表,通过 `url` 属性指定了获取数据的 PHP 文件。在工具栏中,添加了新增、编辑和删除按钮,分别对应三个 JavaScript 函数 `newAccount()`、`editAccount()` 和 `destroyAccount()`。新增和编辑时,会弹出一个对话框,使用 `form` 组件来输入账户信息,并通过 `submit` 方法提交表单数据到 `saveAccount.php` 文件进保存。其中,提交表单数据时,使用了 `onSubmit` 属性来验证表单数据的有效性,`success` 回调函数中判断保存结果是否成功,并刷新账户列表。删除时,会弹出一个确认框,确认删除后,通过 `post` 方法将账户 ID 提交到 `destroyAccount.php` 文件进删除操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值