1.使用innerHTML属性创建动态内容
innerHTML.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>Using responseText with innerHTML</title>
<script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function startRequest() {
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET", "innerHTML.xml", true);
xmlHttp.send(null);
}
function handleStateChange() {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
document.getElementById("results").innerHTML = xmlHttp.responseText;
}
}
}
</script>
</head>
<body>
<form action="#">
<input type="button" value="Search for Today's Activities" οnclick="startRequest();"/>
</form>
<div id="results"></div>
</body>
</html>
innerHTML.xml文件:
<table border="1">
<tbody>
<tr>
<th>Activity Name</th>
<th>Location</th>
<th>Time</th>
</tr>
<tr>
<td>Waterskiing</td>
<td>Dock #1</td>
<td>9:00 AM</td>
</tr>
<tr>
<td>Volleyball</td>
<td>East Court</td>
<td>2:00 PM</td>
</tr>
<tr>
<td>Hiking</td>
<td>Trail 3</td>
<td>3:30 PM</td>
</tr>
</tbody>
</table>
2.将响应解析为XML
parseXML.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>Parsing XML Responses with the W3C DOM</title>
<script type="text/javascript">
var xmlHttp;
var requestType = "";
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function startRequest(requestedList) {
requestType = requestedList;
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET", "parseXML.xml", true);
xmlHttp.send(null);
}
function handleStateChange() {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
if(requestType == "north") {
listNorthStates();
}
else if(requestType == "all") {
listAllStates();
}
}
}
}
function listNorthStates() {
var xmlDoc = xmlHttp.responseXML;
var northNode = xmlDoc.getElementsByTagName("north")[0];
var out = "Northern States";
var northStates = northNode.getElementsByTagName("state");
outputList("Northern States", northStates);
}
function listAllStates() {
var xmlDoc = xmlHttp.responseXML;
var allStates = xmlDoc.getElementsByTagName("state");
outputList("All States in Document", allStates);
}
function outputList(title, states) {
var out = title;
var currentState = null;
for(var i = 0; i < states.length; i++) {
currentState = states[i];
out = out + "\n- " + currentState.childNodes[0].nodeValue;
}
alert(out);
}
</script>
</head>
<body>
<h1>Process XML Document of U.S. States</h1>
<br/><br/>
<form action="#">
<input type="button" value="View All Listed States" οnclick="startRequest('all');"/>
<br/><br/>
<input type="button" value="View All Listed Northern States" οnclick="startRequest('north');"/>
</form>
</body>
</html>
parseXML.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<states>
<north>
<state>Minnesota</state>
<state>Iowa</state>
<state>North Dakota</state>
</north>
<south>
<state>Texas</state>
<state>Oklahoma</state>
<state>Louisiana</state>
</south>
<east>
<state>New York</state>
<state>North Carolina</state>
<state>Massachusetts</state>
</east>
<west>
<state>California</state>
<state>Oregon</state>
<state>Nevada</state>
</west>
</states>
3.使用W3C DOM动态编辑页面
dynamicContent.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>Dynamically Editing Page Content</title>
<script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function doSearch() {
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET", "dynamicContent.xml", true);
xmlHttp.send(null);
}
function handleStateChange() {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
clearPreviousResults();
parseResults();
}
}
}
function clearPreviousResults() {
var header = document.getElementById("header");
if(header.hasChildNodes()) {
header.removeChild(header.childNodes[0]);
}
var tableBody = document.getElementById("resultsBody");
while(tableBody.childNodes.length > 0) {
tableBody.removeChild(tableBody.childNodes[0]);
}
}
function parseResults() {
var results = xmlHttp.responseXML;
var property = null;
var address = "";
var price = "";
var comments = "";
var properties = results.getElementsByTagName("property");
for(var i = 0; i < properties.length; i++) {
property = properties[i];
address = property.getElementsByTagName("address")[0].firstChild.nodeValue;
price = property.getElementsByTagName("price")[0].firstChild.nodeValue;
comments = property.getElementsByTagName("comments")[0].firstChild.nodeValue;
addTableRow(address, price, comments);
}
var header = document.createElement("h2");
var headerText = document.createTextNode("Results:");
header.appendChild(headerText);
document.getElementById("header").appendChild(header);
document.getElementById("resultsTable").setAttribute("border", "1");
}
function addTableRow(address, price, comments) {
var row = document.createElement("tr");
var cell = createCellWithText(address);
row.appendChild(cell);
cell = createCellWithText(price);
row.appendChild(cell);
cell = createCellWithText(comments);
row.appendChild(cell);
document.getElementById("resultsBody").appendChild(row);
}
function createCellWithText(text) {
var cell = document.createElement("td");
var textNode = document.createTextNode(text);
cell.appendChild(textNode);
return cell;
}
</script>
</head>
<body>
<h1>Search Real Estate Listings</h1>
<form action="#">
Show listings from
<select>
<option value="50000">$50,000</option>
<option value="100000">$100,000</option>
<option value="150000">$150,000</option>
</select>
to
<select>
<option value="100000">$100,000</option>
<option value="150000">$150,000</option>
<option value="200000">$200,000</option>
</select>
<input type="button" value="Search" οnclick="doSearch();"/>
</form>
<span id="header">
</span>
<table id="resultsTable" width="75%" border="0">
<tbody id="resultsBody">
</tbody>
</table>
</body>
</html>
dynamicContent.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<properties>
<property>
<address>812 Gwyn Ave</address>
<price>$100,000</price>
<comments>Quiet, serene neighborhood</comments>
</property>
<property>
<address>3308 James Ave S</address>
<price>$110,000</price>
<comments>Close to schools, shopping, entertainment</comments>
</property>
<property>
<address>98320 County Rd 113</address>
<price>$115,000</price>
<comments>Small acreage outside of town</comments>
</property>
</properties>
4.发送请求参数
getAndPostExample.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>Sending Request Data Using GET and POST</title>
<script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function createQueryString() {
var firstName = document.getElementById("firstName").value;
var middleName = document.getElementById("middleName").value;
var birthday = document.getElementById("birthday").value;
var queryString = "firstName=" + firstName + "&middleName=" + middleName
+ "&birthday=" + birthday;
return queryString;
}
function doRequestUsingGET() {
createXMLHttpRequest();
var queryString = "GetAndPostExample?";
queryString = queryString + createQueryString()
+ "&timeStamp=" + new Date().getTime();
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.open("GET", queryString, true);
xmlHttp.send(null);
}
function doRequestUsingPOST() {
createXMLHttpRequest();
var url = "GetAndPostExample?timeStamp=" + new Date().getTime();
var queryString = createQueryString();
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send(queryString);
}
function handleStateChange() {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
parseResults();
}
}
}
function parseResults() {
var responseDiv = document.getElementById("serverResponse");
if(responseDiv.hasChildNodes()) {
responseDiv.removeChild(responseDiv.childNodes[0]);
}
var responseText = document.createTextNode(xmlHttp.responseText);
responseDiv.appendChild(responseText);
}
</script>
</head>
<body>
<h1>Enter your first name, middle name, and birthday:</h1>
<table>
<tbody>
<tr>
<td>First name:</td>
<td><input type="text" id="firstName"/>
</tr>
<tr>
<td>Middle name:</td>
<td><input type="text" id="middleName"/>
</tr>
<tr>
<td>Birthday:</td>
<td><input type="text" id="birthday"/>
</tr>
</tbody>
</table>
<form action="#">
<input type="button" value="Send parameters using GET" οnclick="doRequestUsingGET();"/>
<br/><br/>
<input type="button" value="Send parameters using POST" οnclick="doRequestUsingPOST();"/>
</form>
<br/>
<h2>Server Response:</h2>
<div id="serverResponse"></div>
</body>
</html>
servlet文件:
package ajaxbook.chap3;
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetAndPostExample extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response, String method)
throws ServletException, IOException {
//Set content type of the response to text/xml
response.setContentType("text/xml");
//Get the user's input
String firstName = request.getParameter("firstName");
String middleName = request.getParameter("middleName");
String birthday = request.getParameter("birthday");
//Create the response text
String responseText = "Hello " + firstName + " " + middleName
+ ". Your birthday is " + birthday + "."
+ " [Method: " + method + "]";
//Write the response back to the browser
PrintWriter out = response.getWriter();
out.println(responseText);
//Close the writer
out.close();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Process the request in method processRequest
processRequest(request, response, "GET");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Process the request in method processRequest
processRequest(request, response, "POST");
}
}
需要在web.xml文件做如下配置:
<servlet>
<servlet-name>GetAndPostExample</servlet-name>
<servlet-class>ajaxbook.chap3.GetAndPostExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetAndPostExample</servlet-name>
<url-pattern>/GetAndPostExample</url-pattern>
</servlet-mapping>
5.请求参数作为XML发送
postingXML.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>Sending an XML Request</title>
<script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function createXML() {
var xml = "<pets>";
var options = document.getElementById("petTypes").childNodes;
var option = null;
for(var i = 0; i < options.length; i++) {
option = options[i];
if(option.selected) {
xml = xml + "<type>" + option.value + "<\/type>";
}
}
xml = xml + "<\/pets>";
return xml;
}
function sendPetTypes() {
createXMLHttpRequest();
var xml = createXML();
var url = "PostingXMLExample?timeStamp=" + new Date().getTime();
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send(xml);
}
function handleStateChange() {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
parseResults();
}
}
}
function parseResults() {
var responseDiv = document.getElementById("serverResponse");
if(responseDiv.hasChildNodes()) {
responseDiv.removeChild(responseDiv.childNodes[0]);
}
var responseText = document.createTextNode(xmlHttp.responseText);
responseDiv.appendChild(responseText);
}
</script>
</head>
<body>
<h1>Select the types of pets in your home:</h1>
<form action="#">
<select id="petTypes" size="6" multiple="true">
<option value="cats">Cats</option>
<option value="dogs">Dogs</option>
<option value="fish">Fish</option>
<option value="birds">Birds</option>
<option value="hamsters">Hamsters</option>
<option value="rabbits">Rabbits</option>
</select>
<br/><br/>
<input type="button" value="Submit Pets" οnclick="sendPetTypes();"/>
</form>
<h2>Server Response:</h2>
<div id="serverResponse"></div>
</body>
</html>
PostingXMLExample.java文件:
package ajaxbook.chap3;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class PostingXMLExample extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String xml = readXMLFromRequestBody(request);
Document xmlDoc = null;
try {
xmlDoc =
DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new ByteArrayInputStream(xml.getBytes()));
}
catch(ParserConfigurationException e) {
System.out.println("ParserConfigurationException: " + e);
}
catch(SAXException e) {
System.out.println("SAXException: " + e);
}
/* Note how the Java implementation of the W3C DOM has the same methods
* as the JavaScript implementation, such as getElementsByTagName and
* getNodeValue.
*/
NodeList selectedPetTypes = xmlDoc.getElementsByTagName("type");
String type = null;
String responseText = "Selected Pets: ";
for(int i = 0; i < selectedPetTypes.getLength(); i++) {
type = selectedPetTypes.item(i).getFirstChild().getNodeValue();
responseText = responseText + " " + type;
}
response.setContentType("text/xml");
response.getWriter().print(responseText);
}
private String readXMLFromRequestBody(HttpServletRequest request){
StringBuffer xml = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while((line = reader.readLine()) != null) {
xml.append(line);
}
}
catch(Exception e) {
System.out.println("Error reading XML: " + e.toString());
}
return xml.toString();
}
}
web.xml文件里servlet的配置如下:
<servlet>
<servlet-name>PostingXMLExample</servlet-name>
<servlet-class>ajaxbook.chap3.PostingXMLExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PostingXMLExample</servlet-name>
<url-pattern>/PostingXMLExample</url-pattern>
</servlet-mapping>
6.使用JSON向服务器发送数据
jsonExample.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>JSON Example</title>
<script type="text/javascript" src="json.js"></script>
<script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function doJSON() {
var car = getCarObject();
//Use the JSON JavaScript library to stringify the Car object
var carAsJSON = JSON.stringify(car);
alert("Car object as JSON:\n " + carAsJSON);
var url = "JSONExample?timeStamp=" + new Date().getTime();
createXMLHttpRequest();
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send(carAsJSON);
}
function handleStateChange() {
if(xmlHttp.readyState == 4) {
if(xmlHttp.status == 200) {
parseResults();
}
}
}
function parseResults() {
var responseDiv = document.getElementById("serverResponse");
if(responseDiv.hasChildNodes()) {
responseDiv.removeChild(responseDiv.childNodes[0]);
}
var responseText = document.createTextNode(xmlHttp.responseText);
responseDiv.appendChild(responseText);
}
function getCarObject() {
return new Car("Dodge", "Coronet R/T", 1968, "yellow");
}
function Car(make, model, year, color) {
this.make = make;
this.model = model;
this.year = year;
this.color = color;
}
</script>
</head>
<body>
<br/><br/>
<form action="#">
<input type="button" value="Click here to send JSON data to the server"
οnclick="doJSON();"/>
</form>
<h2>Server Response:</h2>
<div id="serverResponse"></div>
</body>
</html>
JSONExample.java文件:
package ajaxbook.chap3;
import java.io.*;
import java.net.*;
import java.text.ParseException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.json.JSONObject;
public class JSONExample extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String json = readJSONStringFromRequestBody(request);
//Use the JSON-Java binding library to create a JSON object in Java
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
}
catch(ParseException pe) {
System.out.println("ParseException: " + pe.toString());
}
String responseText = "You have a " + jsonObject.getInt("year") + " "
+ jsonObject.getString("make") + " " + jsonObject.getString("model")
+ " " + " that is " + jsonObject.getString("color") + " in color.";
response.setContentType("text/xml");
response.getWriter().print(responseText);
}
private String readJSONStringFromRequestBody(HttpServletRequest request){
StringBuffer json = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while((line = reader.readLine()) != null) {
json.append(line);
}
}
catch(Exception e) {
System.out.println("Error reading JSON string: " + e.toString());
}
return json.toString();
}
}
web.xml文件中servlet的配置如下:
<servlet>
<servlet-name>JSONExample</servlet-name>
<servlet-class>ajaxbook.chap3.JSONExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JSONExample</servlet-name>
<url-pattern>/JSONExample</url-pattern>
</servlet-mapping>