jquery easyui 实现增删改查功能

1、前端jsp中代码:增删改查功能用到了datagrid、window、form、message、combobox
<script type="text/javascript">
var win_add=null, win_upt=null, form_add=null, form_upt=null, form=null;
$(document).ready(function(){
//create datagrid
$('#dg').datagrid({
url:'<%=cp%>/role/getAllRole',
title:'用户信息列表',
pageSize:10,
pageList:[5,10,15,20],
pagination:true,//分页控件
rownumbers:true,//行号
//width:1210,
//width:document.body.clientWidth,
height:document.body.clientHeight,
// fitColumns: true, //自动扩大或缩小列的尺寸以适应表格的宽度并且防止水平滚动
nowrap: false, //True 就会把数据显示在一行里
striped: true, //奇偶条显示不同的颜色
collapsible:true, //可折叠
remoteSort: false, //是否从服务器给数据排序
// singleSelect:false, //是否允许选中多行
//queryParams:{},
idField:'id',
loadMsg:'正在加载....',

columns : [ [
{field:'ck',checkbox:true,width:2}, //显示复选框

{
title : '用户名',
field : 'username',
width : 250,
sortable : true,
align : 'center'
}, {
title : '角色',
field : 'comments',
width : 300,
sortable : false,
align : 'center'
}, {
title : '电子邮箱',
field : 'email',
width : 300,
sortable : false,
align : 'center'
},
{title:'操作',field:'doaction',align:'center',width:300,
formatter:function(value,row,index){
var d='', e = '<a href="javascript:void(-1)" onclick="updateRole('+index+')">更新</a> ',f='';
f = ' <a href="javascript:void(-1)" onclick="deleterole('+index+')">删除</a>';

return d+e+f;
}
}
] ],

toolbar:[{
id:'btnadd',
text:'新增用户',
iconCls:'icon-add',
handler:newAddRole
},'-',{
text:'显示全部',
iconCls:'icon-reload',
handler:displayAll
},'-'
]
});

$('.searchbox').appendTo('.datagrid-toolbar table td:last');
init_window();
init_form();
/* 更新 下拉列表查询 */
$('#role_comments').combobox({ //下拉列表
method:"post",
url:'<%=cp%>/role/getRoleComments',
valueField:'id',
textField:'text',
editable:true
});
});
/* 初始化窗口控件 */
function init_window(){
var width = 400;
var height = 250;
var top = (document.body.clientHeight-height)/2;
var left = (document.body.clientWidth-width)/2;
win_add = $('#userform').window({
closed:true,
width: width,
height: height,
top: top,
left: left,
modal: true,
//iconCls:'icon-vcard'
});
win_upt = $('#upt_role').window({
closed:true,
width: width,
height: height,
top: top,
left: left,
modal: true,
iconCls:'icon-vcard'
});
}
/* 初始化表单控件 */
function init_form(){
form_add = win_add.find('form');
form_upt = win_upt.find('form');
}
/* 新增用户 */
function newAddRole(){
win_add.window('setTitle','添加新用户');
win_add.window('open');
//form_add.form('clear');
form_add.url = '<%=cp%>/role/addRoole';
form = form_add;
}
//数据保存
function saveData(){
form.form('submit', {
url:form.url,
success:function(data){
//data = unescape(data);
eval('data='+data);
//win_add.window('close');
if (data.success){
//grid.datagrid('reload');
$.messager.alert('成功',data.msg);
closeWindow();
} else {
$.messager.alert('错误',data.msg,'error');
}
}
});
}
/* 关闭表单窗口 */
function closeWindow(){
if(win_add)
win_add.window('close');
if(win_upt)
win_upt.window('close');
}
/* 执行常规查询 */
function normalQuery(value){
$('#dg').datagrid("reload",{
username: value
});
}
/* 显示全部记录 */
function displayAll(){
$('#dg').datagrid("reload",{username:''});
}
/* 更新用户 */
function updateRole(index){
var row =$('#dg').datagrid('getRows')[index]; //获取行
if (row){
win_upt.window('setTitle','更新用户资料');
win_upt.window('open');
form_upt.form('clear');
form_upt.form('load', '<%=cp%>/role/getRole/'+row.id);
form_upt.url = '<%=cp%>/role/updateRole?id='+row.id;
form = form_upt;

$('#span_username')[0].innerHTML = row.username;

} else {
$.messager.show({
title:'警告',
msg:'请您先选择用户资料。'
});
}
}

//删除
function deleterole(index){
$.messager.confirm('提示','您是否确认执行删除操作?',function(r){
if (r){
var row = $('#dg').datagrid('getRows')[index];
if(row && row.id!=null){
$.post('<%=cp%>/role/delRole/'+row.username,function(data){
eval("data="+data); //字符串转换成json对象
if(data.success){
$.messager.alert('提示',data.msg);
//$.messager.show({title:'提示',msg:data.msg,timeout:2000,showType:'fade'});
}else{
$.messager.alert('错误',data.msg,'error');
}
});
}
}
});
}
</script>
</head>
<body style="margin:0">
<input id="q" class="easyui-searchbox" data-options="searcher:normalQuery,prompt:'按用户名查询'" style="width:200px; margin:5px;"></input>
<table id="dg" ></table>
<!-- data item form for insert -->
<div id="userform" class="easyui-window" closed="true" modal="true">
<div style="text-align:center; padding:1px;">
<form id="userinfo_form" method="post">

<table width="90%" cellspacing="1" cellpadding="2" border="0" align="center">
<tr>
<td>用 户 名:</td>
<td><input type="text" name="username" class="easyui-validatebox" required="true" missingMessage="请填写用户名" validType="remote['<%=cp%>/rbac/chkUserProperty?chkColumn=username&rnd='+Math.random(),'colname']" invalidMessage="该用户名已存在" /></td>
</tr>

<tr>
<td>电子邮件:</td>
<td><input type="text" name="email" class="easyui-validatebox" validType="email" invalidMessage="邮箱格式错误" /></td>
</tr>
<tr>
<td>住宅电话:</td>
<td><input type="text" name="hometel" /></td>
</tr>
<tr>
<td>手机号码:</td>
<td><input type="text" name="mobileno" /></td>
</tr>

</table>
</form>
</div>
<div style="text-align:center;padding:5px;">
<a href="javascript:void(0)" onclick="saveData()" id="btn-save" class="easyui-linkbutton" icon="icon-save">保存</a>
<a href="javascript:void(0)" onclick="closeWindow()" id="btn-cancel" class="easyui-linkbutton" icon="icon-cancel">取消</a>
</div>
</div>
<!-- data item form for update -->
<div id="upt_role" class="easyui-window" closed="true" modal="true">
<div style="text-align:center; padding:1px;">
<form id="upt_role" method="post">
<table width="90%" cellspacing="1" cellpadding="2" border="0" align="center">
<tr>
<td>用 户 名:</td>
<td><span id="span_username"></span></td>
</tr>
<tr>
<td>分配角色:</td>
<td><select id="role_comments" name="comments" style="width:150px;"></select></td>
</tr>
<tr>
<td>电子邮件:</td>
<td><input type="text" name="email" class="easyui-validatebox" validType="email" invalidMessage="邮箱格式错误" /></td>
</tr>
</table>
</form>
</div>
<div style="text-align:center;padding:5px;">
<a href="javascript:void(0)" onclick="saveData()" id="btn-save" class="easyui-linkbutton" icon="icon-save">保存</a>
<a href="javascript:void(0)" onclick="closeWindow()" id="btn-cancel" class="easyui-linkbutton" icon="icon-cancel">取消</a>
</div>
</div>
</body>
</html>

2、后台实现:
2.1、controller层:
@Controller
@RequestMapping("/role")
public class roleController {

@Autowired
private LoginService loginservice;
@Autowired
private RoleService roleService;

/* 分页查询角色 */
@RequestMapping(value = "getAllRole", method = { RequestMethod.POST })
@ResponseBody
public JsonGrid<Role> getAllRole(
@RequestParam(required = true) Integer page,
@RequestParam(required = true) Integer rows, Role role) {
PaginationSupport<Role> pager = roleService.getPagesRole(role.getUsername(), page, rows);
return new JsonGrid<Role>(pager);
}

/* 增加用户 */
@RequestMapping(value = "addRoole", method = { RequestMethod.POST })
@ResponseBody
public String addRole(Role role) {
roleService.addRole(role);
return "{success:true,msg:'添加成功'}";
}
/*获取用户信息*/
@RequestMapping(value="getRole/{id}", method = { RequestMethod.GET })
public @ResponseBody Role getUser(@PathVariable String id){
Role role = roleService.findRoleById(id);
if(role==null) return new Role();
return role;
}
/*更新用户信息*/
@RequestMapping(value="updateRole",method=RequestMethod.POST)
public @ResponseBody String updateRole(Role role){
if(role==null ){
return "{success:false,msg:'"+Escape.escape("提供资料不全,请重试修改。")+"'}";
}
try {
roleService.updateRole(role);
return "{success:true,msg:'更新成功'}";
} catch (Exception e) {
return "{success:false,msg:'"+Escape.escape(e.getMessage())+"'}";
}
}
/*获取用户角色*/
@RequestMapping(value = "getRoleComments", method = { RequestMethod.POST })
public @ResponseBody List<Role> getAllRolesList() {
List<Role> users = roleService.findAllRoleComments();
return users;
}
/*删除用户*/
@RequestMapping(value="delRole/{uid}", method = { RequestMethod.POST })
public @ResponseBody String delRole(@PathVariable String uid){

try {

roleService.delRole(uid);
return "{success:true,msg:'删除成功'}";
} catch (Exception e) {
e.printStackTrace();
return "{success:false,msg:'"+e.getMessage()+"'}";
}
}

}


2.2、service层:
@Service("roleService")
public class RoleServiceImpl implements RoleService{

@Resource(name="genericDao")
private IGenericDao genericDao;

@Override
public PaginationSupport<Role> getPagesRole(String username,
int pageNumber, int pageSize) {
String queryString = "select u.username,u.comments,u.email from t_user u where 1=1 ";
if(StringUtils.isNotEmpty(username)){
queryString += " and USERNAME like '%"+username+"%'";
}
return genericDao.queryListByRows(queryString , Role.class, pageNumber, pageSize);
}

@Override
public Role getRole(String roleid) {
return genericDao.find("select u.username,u.comments,u.email from t_user u where u.ID = ?", Role.class, roleid);
}

@Override
public Role findRoleById(String roleid) {
return genericDao.find("select u.username,u.comments,u.email from t_user u where u.ID = ?", Role.class, roleid);
}

@Override
public void addRole(Role role) {
System.out.println(role.getUsername());
System.out.println(role.getEmail());
System.out.println(role.getHometel());
System.out.println(role.getMobileno());

}

@Override
public void delRole(String uid) {
System.out.println(uid);

}

@Override
public void updateRole(Role role) {
System.out.println(role.getUsername());
System.out.println(role.getComments());
System.out.println(role.getEmail());
}

@Override
public List<Role> findAllRoleComments() {
// TODO Auto-generated method stub
return genericDao.query("select * from t_role", Role.class);
}

}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值