先看效果:
点击保存使用ajax保存当前表数据,返回一个table格式的html,替换掉页面上的table(已添加的教育经历)。
JSP主要代码:
<div class="container" style="width: 100%;"> <div class="row mg15"> <div class="mainBox_C_C"> <div class="setupBox"> <div class="setItems"> <div class="setFold setUnfold" rel="base"> <h2>教育经历</h2> </div> <div class="setItemsInfo"> <div id="personal_education" > <h6 style="color: #191919;font-size: 100%;font-weight: bold;">已添加的教育经历:</h6> <div id="data-table-education" class="data-table"> <table> <thead> <tr> <th data-property='beginDate'>开始时间</th> <th data-property='endDate'>结束时间</th> <th data-property='school'>学校</th> <th data-property='major'>专业</th> <th data-property='description'>描述</th> <th class='data-action'>操作</th> </tr> </thead> <c:forEach items="${educations }" var="eh" varStatus="status"> <tr id="${eh.objectId }"> <td>${fn:substringBefore(eh.beginDate,' ')}</td> <td>${fn:substringBefore(eh.endDate,' ')}</td> <td>${eh.school }</td> <td>${eh.major }</td> <td>${eh.description }</td> <td> <a class='action-delete' title='删除' href='${dynamicDomain}/member/deleteTr/1/${eh.objectId }'></a> <a class='action-update' title='更新' href='#'></a> </td> </tr> </c:forEach> </table> </div> <h6 style="color: #191919;font-size: 100%;font-weight: bold;">教育经历</h6> <form action="${dynamicDomain}/member/savePersonalEH" method="post" accept-charset="utf-8" class="horizontal-form validator_form" id="personal_education_form"> <div class="a_info_form"> <input type="hidden" id="userId" name="userId" value="${user.objectId }"/> <div class="input-group" > <label for="beginDate">开始时间<span>*</span></label> <div class="inputs"> <input type="text" id="beginDate" name="beginDate" class="a_input_width2" readonly="readonly" onClick="WdatePicker({dateFmt:'yyyy-MM-dd',maxDate:'#F{$dp.$D(\'endDate\')}',readOnly:true})" /> <span class="input-error"><div id="beginDateTip"></div></span> </div> </div> <div class="input-group" > <label for="endDate">结束时间<span>*</span></label> <div class="inputs"> <input type="text" id="endDate" name="endDate" class="a_input_width2" readonly="readonly" onClick="WdatePicker({dateFmt:'yyyy-MM-dd',minDate:'#F{$dp.$D(\'beginDate\')}',readOnly:true})" /> <span class="input-error"><div id="endDateTip"></div></span> </div> </div> <div class="input-group" > <label for="school">学校<span>*</span></label> <div class="inputs"> <input id="school" name="school" type="text" maxlength="50" /> <span class="input-error"><div id="schoolTip"></div></span> </div> </div> <div class="input-group"> <label for="major">专业<span>*</span></label> <div class="inputs"> <input id="major" name="major" type="text" maxlength="50"/> <span class="input-error"><div id="majorTip"></div></span> </div> </div> <div class="input-group"> <label for="description">描述<span>*</span></label> <div class="inputs"> <textarea id="description" name="description" ></textarea> <span class="input-error"><div id="descriptionTip"></div></span> </div> </div> </div> <div class="form-submit" style="text-align: left;"> <button id="user_education_button" class="btn-icon submit all_submit_btn a_person_info_button" type="button">保存</button> </div> </form> </div> </div> </div> <div class="c"></div> </div> </div> </div> <div id="dialog-confirm" title="删除确认项"> <p><span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>你确定要删除这个选项吗?</p> </div> </div> <script type="text/javascript"> $(function(){ $('.action-update').live('click',function(){ var trid = $(this).parent('td').parent('tr').attr('id'); var updateurl = $(this).attr('href'); $('#beginDate').attr('value',$(this).parent('td').siblings('td').eq(0).text()); $('#endDate').attr('value',$(this).parent('td').siblings('td').eq(1).text()); $('#school').attr('value',$(this).parent('td').siblings('td').eq(2).text()); $('#major').attr('value',$(this).parent('td').siblings('td').eq(3).text()); $('#description').attr('value',$(this).parent('td').siblings('td').eq(4).text()); $('#user_education_button').attr('data-id',trid); return false; }); $('#user_education_button').click(function(){ var data; if($(this).attr('data-id')){ data = { action:'update',objectId:$(this).attr('data-id'),userId:$('#userId').val(),school:$('#school').val(),user_beginDate:$('#beginDate').val(),user_endDate:$('#endDate').val(),major:$('#major').val(),description:$('#description').val() }; }else{ data = { userId:$('#userId').val(),description:$('#description').val() }; } $.ajax({ url:$('#personal_education_form').attr('action'),type:'POST',data:data,success:function(data){ if(data){ $("#data-table-education").html(data); $('#school').val(''); $('#beginDate').val(''); $('#endDate').val(''); $('#major').val(''); $('#description').val(''); $("#user_education_button").removeAttr('data-id'); $( "#personal_education_form" ).before('<div class="notification success png_bg"> <a href="#" class="close"><img src="http://www.50jin.com/application/templates/default/images/icons/cross_grey_small.png" title="Close this notification" alt="close"></a><div>保存内容成功! </div></div>'); $(".notification").fadeOut(5000); }else{ $( "#personal_education_form" ).before('<div class="notification notification-error png_bg"> <a href="#" class="close"><img src="http://www.50jin.com/application/templates/default/images/icons/cross_grey_small.png" title="Close this notification" alt="close"></a><div>你填写的内容不符合要求或者没有更新数据,保存失败! </div></div>'); $(".notification").fadeOut(5000); } $("#user_education_button").removeAttr('data-id'); } }) }) }) </script>这个方法,用来点击修改按钮时,给下方的输入表单赋值。并且给“保存”按钮加一个data-id的属性。
$('.action-update').live('click',trid); return false; });点击保存时,根据data-id是否存在,判断是新增还是修改记录。
点击删除按钮的js,放在公共的js外部文件中,因为可以公用。还有关闭提示框的js也可以公用,都放在一起了。如下:
$(function(){ $(".close").live('click',function () { $(this).parent().fadeTo(400,function () { // Links with the class "close" will close parent $(this).slideUp(400,function(){ $('.notification ').remove(); }); }); return false; } ); $('tbody tr:even').addClass("alt-row"); // Add class "alt-row" to even table rows $('.action-delete').live('click',function(){ var trid = $(this).parent('td').parent('tr').attr('id'); var delurl = $(this).attr('href'); $( "#dialog-confirm" ).dialog({ resizable: false,height:170,modal: true,buttons: { "确定": function() { $.ajax({ url:delurl,success:function(data){ $('#'+trid).hide("slow",function(){ $(this).remove(); }); } }) $( this ).dialog( "close" ); },"取消": function() { $( this ).dialog( "close" ); } } }); return false; }); })
进入页面,给table设个list的值,遍历显示表数据(也可以在jsp页面,直接用load方法把table读出来,方法在下面的ajaxTable)
@RequestMapping(value = "educationHistory") public String educationHistory(HttpServletRequest request,HttpServletResponse response) throws Exception { User user = (User)request.getSession().getAttribute(SecurityConstants.SESSION_USER); request.setAttribute("user",user); request.setAttribute("educations",educationManager.getByUserId(user.getObjectId())); return "member/educationHistory"; }
然后在jsp页面点击“保存”时,保存一条记录,跳到下面这个方法
@RequestMapping(value = "savePersonalEH") public String savePersonalEH(HttpServletRequest request,HttpServletResponse response,ModelMap modelMap,Education education) throws Exception { String user_beginDate = request.getParameter("user_beginDate"); String user_endDate = request.getParameter("user_endDate"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date endDate = null; Date beginDate = null; try { beginDate = sdf.parse(user_beginDate); endDate = sdf.parse(user_endDate); } catch (ParseException e) { e.printStackTrace(); } education.setBeginDate(beginDate); education.setEndDate(endDate); educationManager.save(education); return "redirect:/member/ajaxTable/1"; }
在返回值里重定向到了 member/ajaxTable/1这个方法里,这个方法如下:
@RequestMapping(value = "ajaxTable/{table}") public String ajaxTable(HttpServletRequest request,@PathVariable Integer table) throws Exception { User user = (User)request.getSession().getAttribute(SecurityConstants.SESSION_USER); if (table==TABLE_EDUCATION) { request.setAttribute("educations",educationManager.getByUserId(user.getObjectId())); } if (table==TABLE_WORK) { request.setAttribute("works",workHistoryManager.getByUserId(user.getObjectId())); } if (table==TABLE_CERTIFICATION) { request.setAttribute("certifications",certificationManager.getByUserId(user.getObjectId())); } return "member/ajaxTable"; }
private static final int TABLE_EDUCATION = 1; private static final int TABLE_WORK = 2; private static final int TABLE_CERTIFICATION = 3;
这是分别可以处理“教育经历”,“工作经历”,“个人证书”的,看自己需求啦~这三个页面都是这种布局。
这个方法跳到member目录下的ajaxTable.jsp文件里,这个文件的HTML代码就是作为ajax的返回值。
ajaxTable.jsp:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%> <%@ taglib uri="framework" prefix="jdf" %> <c:if test="${not empty educations }"> <table> <thead> <tr> <th data-property='beginDate'>开始时间</th> <th data-property='endDate'>结束时间</th> <th data-property='school'>学校</th> <th data-property='major'>专业</th> <th data-property='description'>描述</th> <th class='data-action'>操作</th> </tr> </thead> <c:forEach items="${educations}" var="eh" varStatus="status"> <tr id="${eh.objectId }"> <td>${fn:substringBefore(eh.beginDate,' ')}</td> <td>${fn:substringBefore(eh.endDate,' ')}</td> <td>${eh.school }</td> <td>${eh.major }</td> <td>${eh.description }</td> <td> <a class='action-delete' title='删除' href='${dynamicDomain}/member/deleteTr/1/${eh.objectId }'></a> <a class='action-update' title='更新' href='#'></a> </td> </tr> </c:forEach> </table> </c:if> <c:if test="${not empty works }"> <table> <thead> <tr> <th data-property='beginDate'>开始时间</th> <th data-property='endDate'>结束时间</th> <th data-property='company'>公司</th> <th data-property='type'>公司性质</th> <th data-property='size'>公司规模</th> <th data-property='industry'>行业</th> <th data-property='department'>部门</th> <th data-property='title'>职位</th> <th data-property='description'>工作描述</th> <th class='data-action'>操作</th> </tr> </thead> <c:forEach items="${works}" var="wh" varStatus="status"> <tr id="${wh.objectId }"> <td>${fn:substringBefore(wh.beginDate,' ')}</td> <td>${fn:substringBefore(wh.endDate,' ')}</td> <td>${wh.company }</td> <td><jdf:columnValue dictionaryId="1001" value="${wh.type }" /></td> <td><jdf:columnValue dictionaryId="1002" value="${wh.size }" /></td> <td>${wh.industry }</td> <td>${wh.department }</td> <td>${wh.title }</td> <td>${wh.description }</td> <td> <a class='action-delete' title='删除' href='${dynamicDomain}/member/deleteTr/2/${wh.objectId }'></a> <a class='action-update' title='更新' href='#'></a> </td> </tr> </c:forEach> </table> </c:if> <c:if test="${not empty certifications }"> <table> <thead> <tr> <th data-property='beginDate'>获得时间</th> <th data-property='name'>证书名称</th> <th data-property='score'>成绩</th> <th data-property='description'>描述</th> <th class='data-action'>操作</th> </tr> </thead> <c:forEach items="${certifications}" var="c" varStatus="status"> <tr id="${c.objectId }"> <td>${fn:substringBefore(c.beginDate,' ')}</td> <td>${c.name }</td> <td>${c.score }</td> <td>${c.description }</td> <td> <a class='action-delete' title='删除' href='${dynamicDomain}/member/deleteTr/3/${c.objectId }'></a> <a class='action-update' title='更新' href='#'></a> </td> </tr> </c:forEach> </table> </c:if>
还有删除按钮的后台代码:
@RequestMapping(value = "deleteTr/{table}/{objectId}") public String deleteTr(HttpServletRequest request,@PathVariable Integer table,@PathVariable Long objectId) throws Exception { if (table==TABLE_EDUCATION) { educationManager.delete(objectId); } if (table==TABLE_WORK) { workHistoryManager.delete(objectId); } if (table==TABLE_CERTIFICATION) { certificationManager.delete(objectId); } modelMap.addAttribute("result",true); return "jsonView"; }
最后看看效果:
点击修改按钮时,表单出现信息:
保存之后,用chrome查看返回的数据如下:
保存成功之后:
点击删除按钮:
———————————————————————————————————————————————————————————————————————————
其他思路:
现在做的是点击保存,就重新载入一个完整的table。
我觉得也可以单行操作,使用insertRow()和deleteRow()方法。
可以参考W3C:
insertRow() http://www.w3school.com.cn/tiy/t.asp?f=hdom_table_insertrow
deleteRow() http://www.w3school.com.cn/tiy/t.asp?f=hdom_table_deleterow
我们原本的点击修改按钮的js不用变,新增的时候,调用insertRow方法,可以使用ajax的datatype为json,从后台传一个对象把对象放到table里。
插入新行:
删除一行:
原文链接:https://www.f2er.com/springmvc/164611.html