如前所述,如果页面中只有一小部分需要修改,此时Ajax技术最适用。换句话说,以前实现一些用例时,为了更新页面中的一小部分总是需要使用完全页面刷新,这些用例就很适合采用Ajax技术。
考虑一个有单个页面的用例,用户向这个页面输入的信息要增加到列表中。在这个例子中,你会看到列出某个组织中员工的Web页面。页面最上面有3个输入框,分别接受员工的姓名、职位和部门。点击Add(增加)按钮,将员工的姓名、职位和部门数据提交到服务器,在这里将这些员工信息增加到数据库中。
当使用传统的Web应用技术时,服务器以重新创建整个页面来做出响应,与前一个页面相比,惟一的差别只是新员工信息会增加到列表中。在这个例子中,我们要使用Ajax技术异步地将员工数据提交到服务器,并把该数据插入到数据库中。服务器发送一个状态码向浏览器做出响应,指示数据库操作是否成功。假设数据库成功插入,浏览器会使用JavaScript DOM操作用新员工信息动态更新页面内容。这个例子中还创建了Delete(删除)按钮,以便从数据库中删除员工信息。
代码清单4-13显示了HTML Web页面的源代码。这个页面有两部分:第一部分包括一些输入框,分别接受员工姓名、职位和部门的数据,以及启动数据库插入的Add按钮;第二部分列出数据库中的所有员工,每个记录有自己的Delete按钮,从而能从数据库删除这个记录的信息。
代码清单4-13 employeeList.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Employee List</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 = "EmployeeList?"
+ createAddQueryString(name, title, department, "add")
+ "&ts=" + new Date().getTime();
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleAddStateChange;
xmlHttp.open("GET", url, true);
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 = "EmployeeList?"
+ "action=delete"
+ "&id=" + id
+ "&ts=" + new Date().getTime();
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleDeleteStateChange;
xmlHttp.open("GET", url, true);
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.onclick = 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" onclick="addEmployee();"/>
</td>
</tr>
</table>
</form>
<span id="employeeListSpan" style="display:none;">
<h2>Employees:</h2>
<table border="1" width="80%">
<tbody id="employeeList"></tbody>
</table>
</span>
</body>
</html>