先来看看最基本的innerHTML用法
innerHTML.xml
下面的例子看看如何用DOM API来修改页面中的信息
接下来一个例子实现的是:通过JSON来做到客户端与服务端的大量数据提交,而不再是简单的 .action?id=1&name=wxy&color=red 而是可以传递类似XML的数据结构,甚至对象的传递
<!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;
} 这个地方通过DOM API得到元素
}
}
</script>
</head>
<body>
<form action="#">
<input type="button" value="Search for Today's Activities" onclick="startRequest();"/>
</form>
<div id="results"></div>
</body>
</html>
"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;
} 这个地方通过DOM API得到元素
}
}
</script>
</head>
<body>
<form action="#">
<input type="button" value="Search for Today's Activities" onclick="startRequest();"/>
</form>
<div id="results"></div>
</body>
</html>
innerHTML.xml
<table border="1">
<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>
</table>
<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>
</table>
下面的例子看看如何用DOM API来修改页面中的信息
<!
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" onclick ="doSearch();" />
</ form >
< span id ="header" >
</ span >
< table id ="resultsTable" width ="75%" border ="0" >
< tbody id ="resultsBody" >
</ tbody >
</ table >
</ body >
</ html >
"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" onclick ="doSearch();" />
</ form >
< span id ="header" >
</ span >
< table id ="resultsTable" width ="75%" border ="0" >
< tbody id ="resultsBody" >
</ tbody >
</ table >
</ body >
</ html >
<?
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 >
< 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 >
接下来一个例子实现的是:通过JSON来做到客户端与服务端的大量数据提交,而不再是简单的 .action?id=1&name=wxy&color=red 而是可以传递类似XML的数据结构,甚至对象的传递
<!
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);
将对象通过JSON转化传递到服务器上去,在那里再进行解析
alert("Car object as JSON: " + 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);
} 注意这里的POST 与 GET 是不同的。
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"
onclick ="doJSON();" />
</ form >
< h2 > Server Response: </ h2 >
< div id ="serverResponse" ></ div >
</ body >
</ html >
"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);
将对象通过JSON转化传递到服务器上去,在那里再进行解析
alert("Car object as JSON: " + 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);
} 注意这里的POST 与 GET 是不同的。
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"
onclick ="doJSON();" />
</ form >
< h2 > Server Response: </ h2 >
< div id ="serverResponse" ></ div >
</ body >
</ html >
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();
}
}
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();
}
}