天天看點

Struts2中使用ajax+json方式批量删除table資料

       今天來給大家分享用ajax+json方式批量删除table資料,可能做過管理系統網站的朋友都遇到過,在頁面中要顯示一張table,并且可以對其進行增删改查。再删除時,可以使用複選框進行批量删除,下面我來介紹一下具體步驟。

       首先,在資料庫中有一張Administrator的表,對應的model類如下:

package com.ims.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * Administrator entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "administrator", catalog = "insmanasys")
public class Administrator implements java.io.Serializable {

	private String adminId;
	private String adminName;
	private String adminPassword;
	private String adminTele;
	private String adminEmail;
	private String adminFax;
	private String adminDep;
	private String adminFirstDepl;
	private String adminSecondDep;
	private Integer adminLevel;

	// Constructors

	/** default constructor */
	public Administrator() {
	}

	/** minimal constructor */
	public Administrator(String adminId, String adminName, String adminTele,
			String adminEmail, String adminDep, String adminFirstDepl,
			String adminSecondDep, Integer adminLevel) {
		this.adminId = adminId;
		this.adminName = adminName;
		this.adminTele = adminTele;
		this.adminEmail = adminEmail;
		this.adminDep = adminDep;
		this.adminFirstDepl = adminFirstDepl;
		this.adminSecondDep = adminSecondDep;
		this.adminLevel = adminLevel;
	}

	/** full constructor */
	public Administrator(String adminId, String adminName,
			String adminPassword, String adminTele, String adminEmail,
			String adminFax, String adminDep, String adminFirstDepl,
			String adminSecondDep, Integer adminLevel) {
		this.adminId = adminId;
		this.adminName = adminName;
		this.adminPassword = adminPassword;
		this.adminTele = adminTele;
		this.adminEmail = adminEmail;
		this.adminFax = adminFax;
		this.adminDep = adminDep;
		this.adminFirstDepl = adminFirstDepl;
		this.adminSecondDep = adminSecondDep;
		this.adminLevel = adminLevel;
	}

	// Property accessors
	@Id
	@Column(name = "AdminID", unique = true, nullable = false, length = 50)
	public String getAdminId() {
		return this.adminId;
	}

	public void setAdminId(String adminId) {
		this.adminId = adminId;
	}

	@Column(name = "Admin_Name", nullable = false, length = 20)
	public String getAdminName() {
		return this.adminName;
	}

	public void setAdminName(String adminName) {
		this.adminName = adminName;
	}

	@Column(name = "Admin_Password", length = 30)
	public String getAdminPassword() {
		return this.adminPassword;
	}

	public void setAdminPassword(String adminPassword) {
		this.adminPassword = adminPassword;
	}

	@Column(name = "Admin_Tele", nullable = false, length = 15)
	public String getAdminTele() {
		return this.adminTele;
	}

	public void setAdminTele(String adminTele) {
		this.adminTele = adminTele;
	}

	@Column(name = "Admin_Email", nullable = false, length = 30)
	public String getAdminEmail() {
		return this.adminEmail;
	}

	public void setAdminEmail(String adminEmail) {
		this.adminEmail = adminEmail;
	}

	@Column(name = "Admin_fax", length = 20)
	public String getAdminFax() {
		return this.adminFax;
	}

	public void setAdminFax(String adminFax) {
		this.adminFax = adminFax;
	}

	@Column(name = "Admin_dep", length = 20)
	public String getAdminDep() {
		return this.adminDep;
	}

	public void setAdminDep(String adminDep) {
		this.adminDep = adminDep;
	}

	@Column(name = "Admin_FirstDepl", length = 20)
	public String getAdminFirstDepl() {
		return this.adminFirstDepl;
	}

	public void setAdminFirstDepl(String adminFirstDepl) {
		this.adminFirstDepl = adminFirstDepl;
	}

	@Column(name = "Admin_SecondDep", length = 20)
	public String getAdminSecondDep() {
		return this.adminSecondDep;
	}

	public void setAdminSecondDep(String adminSecondDep) {
		this.adminSecondDep = adminSecondDep;
	}

	@Column(name = "Admin_Level", nullable = false)
	public Integer getAdminLevel() {
		return this.adminLevel;
	}

	public void setAdminLevel(Integer adminLevel) {
		this.adminLevel = adminLevel;
	}

}
           

DAO和Service層就不在這裡展示了,那麼接下來就是前台展示這張表的頁面:

<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
<%@taglib uri="/struts-tags" prefix="s"%>
<!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">
<title></title>
<link href="css/style.css" target="_blank" rel="external nofollow"  rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/adminMana.js"></script>
</head>
<body>
<div class="place">
    <span>位置:</span>
    <ul class="placeul">
    <li><a href="center.jsp" target="_blank" rel="external nofollow" >首頁</a></li>
    <li><a href="#" target="_blank" rel="external nofollow" >管理者賬号清單</a></li>
    </ul>
</div>
<div class="formbody">
 <div class="formtitle"><span>管理者賬号清單</span></div>
 <div class="rightinfo">
 <div class="tools">
  	<ul class="toolbar">
      <li class="add"><span><img src="images/t01.png" /></span>添加</li>
      <li class="update"><span><img src="images/t02.png" /></span>修改</li>
      <li class="delete"><span><img src="images/t03.png" /></span>删除</li>
      <li class="changePwd"><span><img src="images/t02.png" /></span>修改密碼</li>
    </ul>
    
 </div>
 <table class="imgtable" id="mytable">
 <thead>
    <tr>
    <th></th>
    <th>管理者ID</th>
    <th>真實姓名</th>
    <th>聯系方式</th>
    <th>電子郵件</th>
    <th>所屬機關</th> 
    <th>一級部門</th> 
    <th>二級部門</th> 
    <th>操作</th>
    </tr>
 </thead>
 <tbody id="table2">
 <s:iterator value="administrators">
 <tr>
 <td><input type = "checkbox" value=""  name="s"></td>
 <td><s:property value="adminId"/></td>
 <td><s:property value="adminName"/></td>
 <td><s:property value="adminTele"/></td>
 <td><s:property value="adminEmail"/></td>
 <td><s:property value="adminDep"/></td>
 <td><s:property value="adminFirstDepl"/></td>
 <td><s:property value="adminSecondDep"/></td>
 <td><a  onClick="detail(this)" style="cursor:pointer">詳情</a></td>
 </tr>
 </s:iterator>
 </tbody>
 </table>
 </div>
</div>
</body>
</html>
           

頁面js代碼:

function detail(btn){
	var tr=btn.parentNode.parentNode;
	var table=document.getElementById("mytable");
	var id=table.rows[tr.rowIndex].cells[1].textContent;
	window.location.href="AdminManageAction!showInfo.action?adminId=" target="_blank" rel="external nofollow" +id;
}
$(document).ready(function(){
	$(".add").click(function(){
		window.location.href="AdminManageAction!addHop.action" target="_blank" rel="external nofollow" ;
	});
	$(".delete").click(function(){
		var el = document.getElementsByName("s");
		var count = 0;
		for(var i =0;i<el.length;i++){
			if(el[i].checked)
				count++;
		}
		if(count==0)
			alert("請選中一項!");
		else if(count>=1){
			if(!confirm("确認要删除?")){ 
				window.event.returnValue = false; 
			}
			else{
				var jsonParms = "{" + "\"adminId\":[";
				var index = 0;
				for(var i =0;i<el.length;i++){
					if(el[i].checked){
						index++;
						var td = el[i].parentNode;
						var tr=el[i].parentNode.parentNode;
						var table=document.getElementById("mytable");
						var id=table.rows[tr.rowIndex].cells[1].textContent;
						if(index!=count)
							jsonParms += "\"" + id + "\",";
						else
							jsonParms += "\"" + id + "\"]}";	
					}
				}
				$.post(  
						"AdminManageAction!deleteAdmin.action",
						{json:jsonParms},
						callback,
						"json"
				);
			}
		}
		function callback(json){
			if(json.suc==0){
				alert("對不起,您不能删除自己的賬戶!");
				return false;
			}
			var el = document.getElementsByName("s");
			for(var i = 0;i < el.length;i++){
				if(el[i].checked){
					var tr = el[i].parentNode.parentNode;
					var tbody=tr.parentNode;
					tbody.removeChild(tr);i=i-1;
				}
			}
		}
	});
	$(".update").click(function(){
		var el = document.getElementsByName("s");
		var count = 0;
		for(var i =0;i<el.length;i++){
			if(el[i].checked)
				count++;
		}
		if(count==0)
			alert("請選中一項!");
		else if(count>1)
			alert("請每次選中一項進行更新!");
		else if(count==1){
			for(var j=0;j<el.length;j++){
				if(el[j].checked){
					var tr=el[j].parentNode.parentNode;
					var table=document.getElementById("mytable");
					var id=table.rows[tr.rowIndex].cells[1].textContent;
					window.location.href="AdminManageAction!getUpdateInfo.action?adminId=" target="_blank" rel="external nofollow" +id; 

				}
			}
		}
	});
	$(".changePwd").click(function(){
		var el = document.getElementsByName("s");
		var count = 0;
		for(var i =0;i<el.length;i++){
			if(el[i].checked)
				count++;
		}
		if(count==0)
			alert("請選中一項!");
		else if(count>1)
			alert("請每次選中一項進行更新!");
		else if(count==1){
			for(var j=0;j<el.length;j++){
				if(el[j].checked){
					var tr=el[j].parentNode.parentNode;
					var table=document.getElementById("mytable");
					var id=table.rows[tr.rowIndex].cells[1].textContent;
					window.location.href="changeAdmin_other.action?adminId=" target="_blank" rel="external nofollow" +id;
				}
			}
		}
	});
});
           

請注意上面js代碼中的$(".delete").click()部分,其中var el = document.getElementsByName("s");表示擷取左右名字是"s"的控件,是以我們要把前台頁面中所有的checkbox的name屬性設為"s"。然後接着看下面這一段代碼:

var jsonParms = "{" + "\"adminId\":[";
var index = 0;
for(var i =0;i<el.length;i++){
	if(el[i].checked){
		index++;
		var td = el[i].parentNode;
		var tr=el[i].parentNode.parentNode;
		var table=document.getElementById("mytable");
		var id=table.rows[tr.rowIndex].cells[1].textContent;
		if(index!=count)
			jsonParms += "\"" + id + "\",";
		else
			jsonParms += "\"" + id + "\"]}";	
	}
}
           

這一步是拼接了一段json字元串然後通過ajax方式送出到背景action,用json字元串将要删除的id傳到背景進行删除,删除後背景也會發送一個操作提示的json字元串告訴前台已經完成删除,這時在前台頁面的回調函數中用js函數删除table中的資料即可。下面給大家展示一下背景action代碼:

public String deleteAdmin()throws Exception{
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		String adminId = (String) session.getAttribute("AdminID");
		JSONObject jsonObj = JSONObject.fromObject(json);   
		List list = jsonObj.getJSONArray("adminId");
		for(int i = 0;i < list.size();i++)
		{
			if(list.get(i).toString().equals(adminId)){
				json="{\"suc\":\"0\"}";
				sendMsg(json);
				return null;
			}
		}
		for(int i = 0;i < list.size();i++){
			this.adminService.delete(this.adminService.findById(list.get(i).toString()));
		}
		json="{\"suc\":\"1\"}";
		sendMsg(json);
		return null;
	}
           

上面代碼中從session中取出adminId是為了防止執行操作的管理者删除自己的賬号導緻錯誤,然後接下來用jsonObj.getJSONArray("adminId");取出前台傳過來的要删除的id放入list中,然後循環删除即可。