动态更新web画面

本实例根据文本框入力的值,更新到表格行上。通过表格上的删除按钮可以删除该行记录

 

文件一览

  • employeeList.html
  • EmployeeListServlet

employeeList.html

<!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>Insert title here</title>
<script type="text/javascript">
var xmlHttp;
var name;
var title;
var department;
var deleteID;
var EMP_PREFIX = "emp-";
function createXMLHttpRequest() {
	if (window.ActiveXObject) {
		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	} else if (window.XMLHttpRequest) {
		xmlHttp = new XMLHttpRequest();
	}
}

function addEmployee() {
	name = document.getElementById("name").value;
	title = document.getElementById("title").value;
	department = document.getElementById("dept").value;
	action = "add";
	if (name == "" || title == "" || department == "") {
		return;
	}
	var url = "EmployeeListServlet?" + createAddQueryString(name,title,department,"add") 
		+ "&ts=" + new Date().getTime();
	createXMLHttpRequest();
	xmlHttp.open("GET",url,true);
	xmlHttp.onreadystatechange = handleAddStateChange;
	xmlHttp.send(null); 
}

function createAddQueryString(name,title,department,action) {
	var queryString = "name" + name 
		+ "&title=" + title
		+ "&department=" + department
		+ "&action=" + action;
	return queryString;
}

function handleAddStateChange() {
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			updateEmployeeList();
			clearInputBoxes();
		} else {
			alert("Error While adding employee.");
		}
	}
}

function clearInputBoxes() {
	document.getElementById("name").value = "";
	document.getElementById("title").value = "";
	document.getElementById("dept").value = "";
}

function deleteEmployee(id) {
	deleteID = id;
	var url = "EmployeeListServlet?" + "action=delete" + "&id=" + id + "&ts=" + new Date().getTime();
	createXMLHttpRequest();
	xmlHttp.open("GET",url,true);
	xmlHttp.onreadystatechange = handleDeleteStateChange;
	xmlHttp.send(null);
}

function updateEmployeeList() {
	var responseXML = xmlHttp.responseXML;
	var status = responseXML.getElementsByTagName("status").item(0).firstChild.nodeValue;
	status = parseInt(status);
	if (status != 1) {
		return;
	}
	var row = document.createElement("tr");
	var uniqueId = responseXML.getElementsByTagName("uniqueId")[0].firstChild.nodeValue;
	row.setAttribute("id",EMP_PREFIX+uniqueId);
	row.appendChild(createCellWithText(name));
	row.appendChild(createCellWithText(title));
	row.appendChild(createCellWithText(department));
	
	var deleteButton = document.createElement("input");
	deleteButton.setAttribute("type","button");
	deleteButton.setAttribute("value","Delete");
	deleteButton.οnclick=function() {deleteEmployee(uniqueId);};
	cell = document.createElement("td");
	cell.appendChild(deleteButton);
	row.appendChild(cell);
	
	document.getElementById("employeeList").appendChild(row);
	updateEmployeeListVisibility();
}

function createCellWithText(text) {
	var cell = document.createElement("td");
	cell.appendChild(document.createTextNode(text));
	return cell;
}

function handleDeleteStateChange() {
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			deleteEmployeeFromList();
		} else {
			alert("Error while deleting employee");
		}
	}
}

function deleteEmployeeFromList() {
	var status = xmlHttp.responseXML.getElementsByTagName("status").item(0).firstChild.nodeValue;
	status = parseInt(status);
	if (status != 1) {
		return;
	}
	var rowToDelete = document.getElementById(EMP_PREFIX + deleteID);
	var employeeList = document.getElementById("employeeList");
	employeeList.removeChild(rowToDelete);
	updateEmployeeListVisibility();
}

function updateEmployeeListVisibility() {
	var employeeList = document.getElementById("employeeList");
	if(employeeList.childNodes.length > 0) {
		document.getElementById("employeeListSpan").style.display = "";
	} else {
		document.getElementById("employeeListSpan").style.display = "none";
	}
}
</script>
</head>
<body>
<h1>Employee List</h1>
<form action="#">
	<table width="80%" border="0">
		<tr>
			<td>Name: <input type="text" id="name" /></td>
			<td>Title: <input type="text" id="title" /></td>
			<td>Department: <input type="text" id="dept" /></td>
		</tr>
		<tr>
			<td colspan="3" align="center">
				<input type="button" value="Add" οnclick="addEmployee();" />
			</td>
		</tr>
	</table>
</form>
<span id="employeeListSpan" style="display:none"></span>
<h2>Employees:</h2>
<table border="1" width="80%">
	<tbody id="employeeList"></tbody>
</table>
</body>
</html>

 EmployeeListServlet

package ajaxbook.chap4;

import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class EmployeeListServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String action = req.getParameter("action");
		if ("add".equals(action)) {
			addEmployee(req,resp);
		} else if ("delete".equals(action)) {
			deleteEmployee(req,resp);
		}
	}
	
	protected void addEmployee(HttpServletRequest req, HttpServletResponse resp)
		throws ServletException, IOException {
		//Store the object in the database
		String uniqueID = storeEmployee();
		StringBuffer xml = new StringBuffer("<result><uniqueId>");
		xml.append(uniqueID);
		xml.append("</uniqueId>");
		xml.append("<status>1</status>");
		xml.append("</result>");
		sendResponse(resp,xml.toString());
	}
	
	protected void deleteEmployee(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
		String uniqueID = req.getParameter("id");
		
		StringBuffer xml = new StringBuffer("<result><uniqueId>");
		xml.append(uniqueID);
		xml.append("</uniqueId>");
		xml.append("<status>1</status>");
		xml.append("</result>");
		sendResponse(resp,xml.toString());
	}
	
	private String storeEmployee() {
		String uniqueId = "";
		Random randmier = new Random(System.currentTimeMillis());
		for (int i = 0; i < 8; i++) {
			uniqueId += randmier.nextInt(9);
		}
		return uniqueId;
	}
	
	private void sendResponse(HttpServletResponse resp, String responseText)
	throws ServletException, IOException {
		resp.setContentType("text/xml");
		resp.getWriter().write(responseText);
	}
}

 运行效果参照附件内容

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值