使用Ajax动态更新页面
1.初始化:从数据库中提取信息,在页面中显示,创建添加表单和删除按钮(本例中使用动态数组模拟数据库);
2.添加:在表单中输入数据,提交,服务器验证数据合法性,向数据库中插入数据,返回XML文档给客户端;
客户端接收XML文档,提取信息,判断数据是否成功插入数据库,如果成功则更新页面,根据返回值创建一行数据;
3.删除:点击删除按钮,服务器从数据库中删除该记录,返回XML文档给客户端;
客户端接收XML文档,提取信息,判断数据是否从数据库中成功删除,如果成功则更新页面,删除该行数据;
update.html:
程序代码
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Update</title>
<script src="js/update.js"></script>
</head>
<body onLoad="doInit();">
<h1>Student List</h1>
<form id="form1">
No:<input id="no" type="text" />
Name:<input id="name" type="text" />
Age:<input id="age" type="text" size="5" />
<input type="button" value="ADD" onClick="doAdd();" />
<span id="error"></span>
<h2>Students</h2>
<table id="tab" border="1">
<tbody id="tb">
<tr style="background-color:#bababa">
<th>No.</th>
<th>Name</th>
<th>Age</th>
<th>Operate</th>
</tr>
</tbody>
</table>
</form>
</body>
</html>
update.js:
程序代码
var xmlHttp;
var action;
var delID;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function doInit() {
action = "init";
createXMLHttpRequest();
xmlHttp.onreadystatechange = callback;
var url = "update.mgc?action=init×tamp=" + new Date().getTime();
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function doAdd() {
action = "add";
createXMLHttpRequest();
xmlHttp.onreadystatechange = callback;
var url = "update.mgc?timestamp=" + new Date().getTime();
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var no = document.getElementById("no").value;
var name = document.getElementById("name").value;
var age = document.getElementById("age").value;
var queryString = "action=add&no=" + no + "&name=" + name + "&age=" + age;
xmlHttp.send(queryString);
}
function doDel(no) {
action = "del";
delID = "stu" + no;
createXMLHttpRequest();
xmlHttp.onreadystatechange = callback;
var url = "update.mgc?timestamp=" + new Date().getTime();
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var queryString = "action=del&no=" + no;
xmlHttp.send(queryString);
}
function callback() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
if (action == "init") {
parseInit();
} else if (action == "add") {
parseAdd();
} else if (action == "del") {
parseDel();
}
}
}
}
function parseInit() {
var xmlDoc = xmlHttp.responseXML;
var span = document.getElementById("error").innerHTML = "";
var error = xmlDoc.getElementsByTagName("error")[0].childNodes[0].nodeValue;
if (error != "null") {
}
clearTab();
var stus = xmlDoc.getElementsByTagName("student");
for (var i = 0; i < stus.length; i++) {
var stu = stus[i];
var no = stu.childNodes[0].childNodes[0].nodeValue;
var name = stu.childNodes[1].childNodes[0].nodeValue;
var age = stu.childNodes[2].childNodes[0].nodeValue;
createRow(no, name, age);
}
clearInput();
}
function clearTab() {
var list = document.getElementById("tb");
if (list.hasChildNodes()) {
while (list.childNodes.length > 1) {
list.removeChild(list.childNodes[1]);
}
}
}
function createRow(no, name, age) {
var list = document.getElementById("tb");
var newTr = document.createElement("tr");
newTr.setAttribute("id", "stu" + no);
createCell(newTr, no);
createCell(newTr, name);
createCell(newTr, age);
var newTd = document.createElement("td");
var btn = document.createElement("input");
btn.type = "button";
btn.value= "DEL";
btn.onclick = function() {doDel(no);};
newTd.appendChild(btn);
newTr.appendChild(newTd);
list.appendChild(newTr);
}
function createCell(newTr, tdContent) {
var newTd = document.createElement("td");
var newContent = document.createTextNode(tdContent);
newTd.appendChild(newContent);
newTr.appendChild(newTd);
}
function clearInput() {
document.getElementById("no").value = "";
document.getElementById("name").value = "";
document.getElementById("age").value = "";
}
function parseAdd() {
var list = document.getElementById("tb");
var xmlDoc = xmlHttp.responseXML;
var error = xmlDoc.getElementsByTagName("error")[0].firstChild.nodeValue;
if (error == "null") {
var stu = xmlDoc.getElementsByTagName("student")[0];
var no = stu.childNodes[0].firstChild.nodeValue;
var name = stu.childNodes[1].firstChild.nodeValue;
var age = stu.childNodes[2].firstChild.nodeValue;
createRow(no, name, age);
var span = document.getElementById("error").innerHTML = "";
} else {
var span = document.getElementById("error").innerHTML = error;
}
}
function parseDel() {
var list = document.getElementById("tb");
var xmlDoc = xmlHttp.responseXML;
var error = xmlDoc.getElementsByTagName("error")[0].firstChild.nodeValue;
if (error == "null") {
var delElem = document.getElementById(delID);
list.removeChild(delElem);
var span = document.getElementById("error").innerHTML = "";
}
}
Update.java:
程序代码
package cn.edu.ahau.mgc.ajax.update;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Update extends HttpServlet {
List<Student> stus;
String error = "null";
private void initData() {
stus = new ArrayList<Student>();
stus.add(new Student("1001","Magci",20));
stus.add(new Student("1002","Haha",16));
stus.add(new Student("1003","Heihei",24));
stus.add(new Student("1004","Wawa",22));
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
error = "null";
String action = request.getParameter("action");
StringBuffer xml = new StringBuffer();
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
if ("init".equals(action)) {
this.initData();
xml.append("<response>");
xml.append("<error>" + error + "</error>");
xml.append("<students>");
for (Iterator<Student> iterator = stus.iterator(); iterator.hasNext();) {
Student stu = iterator.next();
xml.append("<student>");
xml.append("<no>" + stu.getNo() + "</no>");
xml.append("<name>" + stu.getName() + "</name>");
xml.append("<age>" + stu.getAge() + "</age>");
xml.append("</student>");
}
xml.append("</students>");
xml.append("</response>");
} else if ("add".equals(action)) {
String no = request.getParameter("no");
String name = request.getParameter("name");
int age = 0;
try {
age = Integer.parseInt(request.getParameter("age"));
} catch (NumberFormatException e) {
age = 20;
}
Student newStu = new Student(no, name, age);
if (newStu.check() && !this.isExist(newStu)) {
stus.add(newStu);
}
xml.append("<response>");
xml.append("<error>" + error + "</error>");
xml.append("<student>");
xml.append("<no>" + no + "</no>");
xml.append("<name>" + name + "</name>");
xml.append("<age>" + age + "</age>");
xml.append("</student>");
xml.append("</response>");
} else if ("del".equals(action)) {
String no = request.getParameter("no");
delete(no);
xml.append("<response>");
xml.append("<error>" + error + "</error>");
xml.append("</response>");
}
PrintWriter out = response.getWriter();
out.print(xml);
out.flush();
out.close();
System.out.println(stus.size());
}
private boolean isExist(Student stu) {
boolean isExist = false;
for (Iterator<Student> iterator = stus.iterator(); iterator.hasNext();) {
Student stuItem = (Student) iterator.next();
if (stuItem.getNo().equals(stu.getNo())) {
error = "Your NO. already exists!";
isExist = true;
}
}
return isExist;
}
private void delete(String no) {
Student reStu = null;
for (Iterator<Student> iterator = stus.iterator(); iterator.hasNext();) {
Student stu = (Student) iterator.next();
if (stu.getNo().equals(no)) {
reStu = stu;
}
}
stus.remove(reStu);
}
class Student {
private String no;
private String name;
private int age;
public Student(String no, String name, int age) {
this.no = no;
this.name = name;
this.age = age;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean check() {
boolean isRight = true;
if (this.no == null || "".equals(this.no) || this.name == null || "".equals(this.name)) {
error = "Please enter No. or Name!";
isRight = false;
}
return isRight;
}
}
}
web.xml:
程序代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>Update</servlet-name>
<servlet-class>cn.edu.ahau.mgc.ajax.update.Update</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Update</servlet-name>
<url-pattern>/update.mgc</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
1.初始化:从数据库中提取信息,在页面中显示,创建添加表单和删除按钮(本例中使用动态数组模拟数据库);
2.添加:在表单中输入数据,提交,服务器验证数据合法性,向数据库中插入数据,返回XML文档给客户端;
客户端接收XML文档,提取信息,判断数据是否成功插入数据库,如果成功则更新页面,根据返回值创建一行数据;
3.删除:点击删除按钮,服务器从数据库中删除该记录,返回XML文档给客户端;
客户端接收XML文档,提取信息,判断数据是否从数据库中成功删除,如果成功则更新页面,删除该行数据;
update.html:
程序代码
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Update</title>
<script src="js/update.js"></script>
</head>
<body onLoad="doInit();">
<h1>Student List</h1>
<form id="form1">
No:<input id="no" type="text" />
Name:<input id="name" type="text" />
Age:<input id="age" type="text" size="5" />
<input type="button" value="ADD" onClick="doAdd();" />
<span id="error"></span>
<h2>Students</h2>
<table id="tab" border="1">
<tbody id="tb">
<tr style="background-color:#bababa">
<th>No.</th>
<th>Name</th>
<th>Age</th>
<th>Operate</th>
</tr>
</tbody>
</table>
</form>
</body>
</html>
update.js:
程序代码
var xmlHttp;
var action;
var delID;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function doInit() {
action = "init";
createXMLHttpRequest();
xmlHttp.onreadystatechange = callback;
var url = "update.mgc?action=init×tamp=" + new Date().getTime();
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function doAdd() {
action = "add";
createXMLHttpRequest();
xmlHttp.onreadystatechange = callback;
var url = "update.mgc?timestamp=" + new Date().getTime();
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var no = document.getElementById("no").value;
var name = document.getElementById("name").value;
var age = document.getElementById("age").value;
var queryString = "action=add&no=" + no + "&name=" + name + "&age=" + age;
xmlHttp.send(queryString);
}
function doDel(no) {
action = "del";
delID = "stu" + no;
createXMLHttpRequest();
xmlHttp.onreadystatechange = callback;
var url = "update.mgc?timestamp=" + new Date().getTime();
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
var queryString = "action=del&no=" + no;
xmlHttp.send(queryString);
}
function callback() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
if (action == "init") {
parseInit();
} else if (action == "add") {
parseAdd();
} else if (action == "del") {
parseDel();
}
}
}
}
function parseInit() {
var xmlDoc = xmlHttp.responseXML;
var span = document.getElementById("error").innerHTML = "";
var error = xmlDoc.getElementsByTagName("error")[0].childNodes[0].nodeValue;
if (error != "null") {
}
clearTab();
var stus = xmlDoc.getElementsByTagName("student");
for (var i = 0; i < stus.length; i++) {
var stu = stus[i];
var no = stu.childNodes[0].childNodes[0].nodeValue;
var name = stu.childNodes[1].childNodes[0].nodeValue;
var age = stu.childNodes[2].childNodes[0].nodeValue;
createRow(no, name, age);
}
clearInput();
}
function clearTab() {
var list = document.getElementById("tb");
if (list.hasChildNodes()) {
while (list.childNodes.length > 1) {
list.removeChild(list.childNodes[1]);
}
}
}
function createRow(no, name, age) {
var list = document.getElementById("tb");
var newTr = document.createElement("tr");
newTr.setAttribute("id", "stu" + no);
createCell(newTr, no);
createCell(newTr, name);
createCell(newTr, age);
var newTd = document.createElement("td");
var btn = document.createElement("input");
btn.type = "button";
btn.value= "DEL";
btn.onclick = function() {doDel(no);};
newTd.appendChild(btn);
newTr.appendChild(newTd);
list.appendChild(newTr);
}
function createCell(newTr, tdContent) {
var newTd = document.createElement("td");
var newContent = document.createTextNode(tdContent);
newTd.appendChild(newContent);
newTr.appendChild(newTd);
}
function clearInput() {
document.getElementById("no").value = "";
document.getElementById("name").value = "";
document.getElementById("age").value = "";
}
function parseAdd() {
var list = document.getElementById("tb");
var xmlDoc = xmlHttp.responseXML;
var error = xmlDoc.getElementsByTagName("error")[0].firstChild.nodeValue;
if (error == "null") {
var stu = xmlDoc.getElementsByTagName("student")[0];
var no = stu.childNodes[0].firstChild.nodeValue;
var name = stu.childNodes[1].firstChild.nodeValue;
var age = stu.childNodes[2].firstChild.nodeValue;
createRow(no, name, age);
var span = document.getElementById("error").innerHTML = "";
} else {
var span = document.getElementById("error").innerHTML = error;
}
}
function parseDel() {
var list = document.getElementById("tb");
var xmlDoc = xmlHttp.responseXML;
var error = xmlDoc.getElementsByTagName("error")[0].firstChild.nodeValue;
if (error == "null") {
var delElem = document.getElementById(delID);
list.removeChild(delElem);
var span = document.getElementById("error").innerHTML = "";
}
}
Update.java:
程序代码
package cn.edu.ahau.mgc.ajax.update;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Update extends HttpServlet {
List<Student> stus;
String error = "null";
private void initData() {
stus = new ArrayList<Student>();
stus.add(new Student("1001","Magci",20));
stus.add(new Student("1002","Haha",16));
stus.add(new Student("1003","Heihei",24));
stus.add(new Student("1004","Wawa",22));
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
error = "null";
String action = request.getParameter("action");
StringBuffer xml = new StringBuffer();
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
if ("init".equals(action)) {
this.initData();
xml.append("<response>");
xml.append("<error>" + error + "</error>");
xml.append("<students>");
for (Iterator<Student> iterator = stus.iterator(); iterator.hasNext();) {
Student stu = iterator.next();
xml.append("<student>");
xml.append("<no>" + stu.getNo() + "</no>");
xml.append("<name>" + stu.getName() + "</name>");
xml.append("<age>" + stu.getAge() + "</age>");
xml.append("</student>");
}
xml.append("</students>");
xml.append("</response>");
} else if ("add".equals(action)) {
String no = request.getParameter("no");
String name = request.getParameter("name");
int age = 0;
try {
age = Integer.parseInt(request.getParameter("age"));
} catch (NumberFormatException e) {
age = 20;
}
Student newStu = new Student(no, name, age);
if (newStu.check() && !this.isExist(newStu)) {
stus.add(newStu);
}
xml.append("<response>");
xml.append("<error>" + error + "</error>");
xml.append("<student>");
xml.append("<no>" + no + "</no>");
xml.append("<name>" + name + "</name>");
xml.append("<age>" + age + "</age>");
xml.append("</student>");
xml.append("</response>");
} else if ("del".equals(action)) {
String no = request.getParameter("no");
delete(no);
xml.append("<response>");
xml.append("<error>" + error + "</error>");
xml.append("</response>");
}
PrintWriter out = response.getWriter();
out.print(xml);
out.flush();
out.close();
System.out.println(stus.size());
}
private boolean isExist(Student stu) {
boolean isExist = false;
for (Iterator<Student> iterator = stus.iterator(); iterator.hasNext();) {
Student stuItem = (Student) iterator.next();
if (stuItem.getNo().equals(stu.getNo())) {
error = "Your NO. already exists!";
isExist = true;
}
}
return isExist;
}
private void delete(String no) {
Student reStu = null;
for (Iterator<Student> iterator = stus.iterator(); iterator.hasNext();) {
Student stu = (Student) iterator.next();
if (stu.getNo().equals(no)) {
reStu = stu;
}
}
stus.remove(reStu);
}
class Student {
private String no;
private String name;
private int age;
public Student(String no, String name, int age) {
this.no = no;
this.name = name;
this.age = age;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean check() {
boolean isRight = true;
if (this.no == null || "".equals(this.no) || this.name == null || "".equals(this.name)) {
error = "Please enter No. or Name!";
isRight = false;
}
return isRight;
}
}
}
web.xml:
程序代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>Update</servlet-name>
<servlet-class>cn.edu.ahau.mgc.ajax.update.Update</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Update</servlet-name>
<url-pattern>/update.mgc</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>