Learning AJAX

来源:互联网 发布:奢侈品图案 知乎 编辑:程序博客网 时间:2024/06/06 17:43


XMLHttpRequest

The XMLHttpRequest object is the key to AJAX. 

XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript and other web browser scripting languages to transfer and manipulate XML data to and from a web server using HTTP, establishing an independent connection channel between a web page's Client-Side and Server-Side.

The data returned from XMLHttpRequest calls will often be provided by back-end databases. Besides XML, XMLHttpRequest can be used to fetch data in other formats, e.g. JSON or even plain text.

You already have seen couple of examples on how to create a XMLHttpRequest object.

Below is listed some of the methods and properties you have to become familiar with.


XMLHttpRequest Methods

  • abort()
    Cancels the current request.

  • getAllResponseHeaders()
    Returns the complete set of HTTP headers as a string.

  • getResponseHeader( headerName )
    Returns the value of the specified HTTP header.

  • open( method, URL )
    open( method, URL, async )
    open( method, URL, async, userName )
    open( method, URL, async, userName, password )
    Specifies the method, URL, and other optional attributes of a request.

    The method parameter can have a value of "GET", "POST", or "HEAD". Other HTTP methods, such as "PUT" and "DELETE" (primarily used in REST applications), may be possible

    The "async" parameter specifies whether the request should be handled asynchronously or not . "true" means that script processing carries on after the send() method, without waiting for a response, and "false" means that the script waits for a response before continuing script processing.

  • send( content )
    Sends the request.

  • setRequestHeader( label, value )
    Adds a label/value pair to the HTTP header to be sent.


XMLHttpRequest Properties

  • onreadystatechange
    An event handler for an event that fires at every state change.

  • readyState

    The readyState property defines the current state of the XMLHttpRequest object.

    Here are the possible values for the readyState propery:

    StateDescription0The request is not initialized1The request has been set up2The request has been sent3The request is in process4The request is completed

    readyState=0 after you have created the XMLHttpRequest object, but before you have called the open() method.

    readyState=1 after you have called the open() method, but before you have called send().

    readyState=2 after you have called send().

    readyState=3 after the browser has established a communication with the server, but before the server has completed the response.

    readyState=4 after the request has been completed, and the response data have been completely received from the server.

  • responseText
    Returns the response as a string.

  • responseXML
    Returns the response as XML. This property returns an XML document object, which can be examined and parsed using W3C DOM node tree methods and properties.

  • status
    Returns the status as a number (e.g. 404 for "Not Found" and 200 for "OK").

  • statusText
    Returns the status as a string (e.g. "Not Found" or "OK").


2 详细描述

在使用 XMLHttpRequest 进行异步处理之前,需要对该对象初始化操作,根据不同的浏览器,初始
化方法是不同的. 
(1)IE 浏览器的初始化方法如下: 

Var xmlHttp = new ActiveXObject(“Msxml2.XMLHTTP”);
 

或者

Var xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”); 

括号中的不同参数是针对不同版本的浏览器。还有其他参数类型,只是现在最为常见的就是这两种,
需要考虑的也就是这两种。 

(2)Mozilla 浏览器初始化方法如下:

Var xmlHttp = new XMLHttpRequest();


总的 XMLHttpRequest 对象初始化程序如下:

<script language="javascript" type="text/javascript"> <!--     var xmlhttp ; try{     xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }catch(e){     try{ xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");     }catch(e){   try{       xmlhttp = new XMLHttpRequest(); }catch(e){}     } } --> </script> 


XMLHttpRequest 对象中所包含的一般方法如下表所示:



其中比较常用的是 open()和 send()两个方法。其中 open()方法在创建完了 XMLHttpRequest 对象之后
就可以使用它了,它创建一个请求,并准备向服务器发送,基本语法如下:

Xmlhttp.open(method,url,asynchronous,user,password);

例如:

Xmlhttp.open(“get”,”getData.jsp?key=8”,true); 


其中参数含义如下: 
   Method:指定请求的类型,一般为 get 或者 post。 
   url:指定请求的地址,可以使用绝对地址或者相对地址,并且可以附带查询字符串。 
   Asynchronous:这是一个可选项,表示请求是同步还是异步,异步请求为 false,同步请求为 true,
默认情况下该参数为 true。 
   User:可选参数,指定请求用户名,没有则省略。 
   Password:可选参数,指定请求的密码,没有则省略。 

在使用 open()方法创建了一个请求之后,就可以使用 send()方法向服务器发送该创建的请求,其基
本语法如下: 

Xmlhttp.send(content); 

其中的 content 变量为记录发送的数据,其格式为查询字符串的形式,如下: 

Content = “username=Johnson&sex=male&age=25”; 

其中定义了发送给服务器的三个名/值对,并且在它们之间使用&符号隔开。如果在 open()方法中method 参数指定为 get,则这些参数是作为字符串提交的,服务器端使用request.querystring()来获取;
如果method 参数指定为post,则这些参数作为HTTP 的post 方法提交,在服务器端需要使用request.form()
方法来获取。这里的 content 参数是必须要指定,如果没有参数值需要传递,可以设置的 content=null,则 xmlhttp.send(null)


XMLHttpRequest 对象中所包含的属性如下所示:



下面对 XMLHttpRequest 对象中的各个属性进行详细介绍: 


(1)onreadystatechange 事件捕获请求的状态变化 
在向服务器端发送了一个请求后,往往是不知道请求什么时候完成,所以必须使用一种机制来获取请求处理的状态。Onreadystatechange 状态变量就是 XMLHttpRequest 对象用来实现这一功能的。 
Onreadystatechange 事件可以指定一个事件处理函数用来处理 XMLHttpRequest 对象的执行结果,例如: 

Xmlhttp. Onreadystatechange=function(){       //此处将对异步请求返回的结果进行处理(根据readyState判断) } Xmlhttp.open(); Xmlhttp.send();

注意:这里将事件绑定在调用了  open()和  send()方法之后进行,是因为这两个方法都会触发Onreadystatechange 事件。如果该事件在其后面定义,则可能引起该事件指定的处理代码得不到执行。 

(2)使用 readyState 属性判断请求状态 
Onreadystatechange 事件是在 readyState 属性发生改变的时候触发执行的,该属性记录着当前请求的
状态,然后在程序中可以根据不同请求状态进行不同的处理。下表列出了各种不同属性值的含义。



在整个过程中,Onreadystatechange 事件在每次 readyState 属性值发生改变的时候都会执行一次,所以通常在事件中判断 readyState 值,然后根据不同状态来作适当的处理。例如:

Xmlhttp.onreadystatechange=function(){     If(xmlhttp.readystate == 4){       //请求完毕时的执行处理代码     } } 


这里的 readyState 仅仅表示请求的状态,并不表示请求的结果,下面介绍的 status 属性时用来判断请求结果。 

(3)使用 status 属性判断请求的结果 

Status 属性存储服务器端返回的 http 请求响应结果码,下表列出了常见的响应结果码含义。




在使用 readyState 属性判断请求完成之后,可以使用 status 属性判断请求处理结果。在 AJAX 开发过程中,最为常见的响应代码为 200,它表示请求处理成功,例如下面的一段 AJAX 代码:

Xmlhttp.onreadystatechange=function(){     If(xmlhttp.readystate == 4){         //判断请求成功完成         If(xmlhttp.status == 200){             //判断请求操作成功         }else{             //操作错误或者未完成         }    } } 


以上代码是一个比较完整的 XMLHttpRequest 对象请求处理代码。


(4)使用 responseText 获得返回的文本 

当服务器已经成功处理完请求之后,就可以使用 XMLHttpRequest 对象中的 responseText 属性来获取返回的文本或者 html 页面数据。例如下面的一段 html 页面代码,该页面文件名为 responseText.html:

<script language=”javascript” type=”text/javascript”> var xmlhttp; try{     xmlhttp = new ActiveXObjt(“Msxml2.XMLHTTP”); }catch(e){     try{         xmlhttp = new ActiveXObject(“Microsoft.XMLHTTP”);       }catch(e){         try{            xmlhttp = new XMLHttpRequest();         }catch(e){}       } } //下面定义 XMLHttpRequest 对象的事件处理程序 xmlhttp.onreadystatechange = function(){       if(xmlhttp.readyState == 4){           if(xmlhttp.status == 200){             var showHtml = xmlhttp.responseText;             alert(showHtml);           }else                alert(“处理错误”);       } } //创建一个请求连接 Xmlhttp.open(“get”,”a.html”,true); Xmlhttp.send(null); </script> 


其中 a.html 静态页面代码如下:

<html> <head> <title>new Document</title> </head> <body>hello,ajax!</body> </html> 


使用 XMLHttpRequest 对象中的 responseText 属性可以获取到请求页面的纯文本信息,并不经过任何处理。并不是每次都要求返回 html 页面代码,有时可以使用 json 获XML数据格式来返回只需要的数据。


(5)使用 responseXML 属性来获取 XML 文档信息 

除了可以使用 responseText 属性来获取纯文本信息之后,还可以使用其中的 responseXML 属性来获取服务器返回的 XML 文档对象。在使用 responseText 属性来获取返回的纯文本信息时,后台服务器是不需要进行额外操作的。但是 responseXML 属性不同,它需要服务器返回的必须是一个严格符合 XML格式的文档,这就要求返回的 HTTP 头的 content-type 设置为“text/XML”。


如果服务器直接获取某个 XML 文档并返回(例如将前面的 a.html 改名为 a.xml),这时因为请求后缀为 xml,所以服务器会自动将返回结果的“content-type”属性设置为“text/xml”。如果是通过后台服务器程序动态生成的 XML,则需要设置 Response[“content-type”]为“text/xml”。 


获取的 responseXML 属性实际上是一个 DOM 文档对象模型说规定的文档对象,具有 DOM 模型的操作规范。这里将 a.html 文件改名为 a.xml,然后修改上面实例中的事件触发函数代码,其他部分不需要修改。 

Xmlhttp.onreadystatechange = function(){       If(xmlhttp.readyState == 4){           If(xmlhttp.status == 200){             Var xmlObj = xmlhttp.responseXML;             Var title = xmlObj.getElementByTagName(“title”)[0].text;             Alert(title);           } Else                Alert(“处理错误”);       } } 

3 DOM文档对象模型

(1)document.getElementById()引用指定 id 的结点 

在 HTML 或者 XHTML 中,每一个结点对象都可以定义一个 id 属性。但是每个结点定义的 id 属性值必须在整个文档中惟一。另外可以使用 document 中的 getElementById()方法来获取到该结点对象。例如:

<html> <head> <title> document.getElementById()方法  <title><script language="javascript"> var divItem = document.getElementById("div1"); alert(divItem.innerHTML); </script> </head> <body> <div id="div1">hello,Ajax!</div> </body> </html> 



(2)document.getElementByTagName()引用指定标签名的结点对象

使用 document.getElementByTagName()可以返回某文档中所有指定标签名的结点对象组,具体示范实例如下:

<html> <head> <title> document.getElementById()方法  <.title> <script language=”javascript”> var divItems = document.getElementByTagName(“div”); for(var i=0;i<divItems.length;i++) alert(divItems[i].innerHTML); </script> </head> <body> <div id=”div1”>hello,Ajax!</div> <div id=”div2”>hello,Ajax2!</div> </body> </html> 


代码说明:由于该页档中存在两个标签名为“div”的结点对象,所以使用document.getElementByTagName()方法返回的是包含两个结点对象的数组,使用 for 循环将这两个结点中的文本信息输出.


(3)处理属性结点

(a)获取和设置属性结点的值

下面还是通过一个简单的实例来演示一下,例如存在如下的一个属性结点:

<img id=”img1” src=”hello.jpg” alt=”demo” />

下面编写 javascript 代码来操作这个结点:

<script language=”javascript” type=”text/javascript”> Var itemImg = document.getElementById(“img1”);            //获取结点对象 Alert(itemImg.src);                                         //输出结点对象中的 src 属性值 itemImg.src = “ok.jpg”;                                   //设置结点对象中的 src 属性值 alert(itemImg.src); </script> 

(b)使用 setAttribute()方法来添加一个新属性

该方法的语法代码如下:

element.setAttribute(attributeName,attributeValue);

代码说明:其中 element 为某一结点对象;attributeName 为新添加的属性名,attributeValue 为给新
添加 attributeName 属性设置的值。


(c)使用 innerHTML 属性来修改结点的文本信息

var itemDiv = Document.getElementById(“div1”) itemDiv.innerHTML = “修改之后的内容”; 


还有很多动态修改标签的层次结构,表格操作等请查阅相关文档。


4 动态增加HTML内容

(1)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>


You use the getElementsByTagName method to retrieve all the property elements in the
XML document as an array and assign the array to the local variable properties. Once you have the array of property elements, you can iterate over each element in the array and retrieve the property’s address, price, and 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);}


Consider the address element, which is a child of the property element. You first get the single address element by calling the getElementsByTagName method on the property element. The getElementsByTagName method returns an array, but since you know that one and only one address element exists, you can reference it using the[0] notation.

Continuing your way down the XML structure, you now have a reference to the address
tag, and you now need to get its textual content. Remembering that text is actually a child node of the parent element, you can access the text node of the address element by using thefirstChild property. Now that you have the text node, you can retrieve the text by refer- ring to the nodeValue property of the text node.

You use the same process to retrieve the values of the price and comments elements, and each value is assigned to the price and comments local variables, respectively. The address, price, and comments are then passed to a helper function named addTableRow that actually builds a table row with the results data.


(2)dynamicContent.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>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>


(3)Methods of DOM Elements Useful for Traversing XML Documents


MethodName

Description

getElementById(id)(document)

Retrievesthe element in the document that has the specified unique IDattribute value

getElementsByTagName(name)

Returnsan array of the current element’s children that have the specified tag name

hasChildNodes()

Returnsa Boolean indicating whether the element has any child elements

getAttribute(name)

Returnsthe value of the element’s attribute specified by name



(4)W3C DOM Properties and Methods Useful When Creating Content Dynamically

Property/Method

Description

document.createElement(tagName)

The createElement method on the document objectcreates the element specified by tagName.

Providing the string div as the method param-eter produces a div element.

document.createTextNode(text)

This document object’s createTextNode method creates a node containing static text.

<element>.appendChild(childNode)

The appendChild method adds the specified node tothe current element’s list of child nodes.

For example, you can add an option element as achild node of a select element.

<element>.getAttribute(name)

<element>.setAttribute(name, value)

These methods, respectively, get and set thevalue of the attribute name of the element.

<element>.insertBefore(newNode, targetNode)

This inserts the node newNode before the element

targetNode as a child of the current element.

<element>.removeAttribute(name)

This removes the attribute name from theelement.

<element>.removeChild(childNode)

This removes the element childNode from theelement.

<element>.replaceChild(newNode, oldNode)

This method replaces the node oldNode with thenode newNode.

<element>.hasChildnodes()

This method returns a Boolean indicating whetherthe element has any child elements.



5 Sending Request Parameters------send(content)

The only difference is that when send-ing the request using GET, the query string will be appended to the request URL, while with POST the query string is sent when calling the XMLHttpRequest object’s send() method.


(1)getAndPostExample.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>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?";//GetAndPostExample is the servlet class namequeryString = 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;");//yes , it is necessaryxmlHttp.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"onclick="doRequestUsingGET();" /> <br /><br /> <input type="button" value="Send parameters using POST"onclick="doRequestUsingPOST();" /></form><br /><h2>Server Response:</h2><div id="serverResponse"></div></body></html>

(2) servlet GetAndPostExample.java

package ajax;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@WebServlet("/GetAndPostExample")public class GetAndPostExample extends HttpServlet {private static final long serialVersionUID = 1L;public GetAndPostExample() {super();}protected void processRequest(HttpServletRequest request,HttpServletResponse response, String method)throws ServletException, IOException {// Set content type of the response to text/xmlresponse.setContentType("text/xml");// Get the user's inputString firstName = request.getParameter("firstName");String middleName = request.getParameter("middleName");String birthday = request.getParameter("birthday");// Create the response textString responseText = "Hello " + firstName + " " + middleName+ ". Your birthday is " + birthday + "." + " [Method: "+ method + "]";//Write the response back to the browserPrintWriter out = response.getWriter();out.println(responseText);//Close the writerout.close();}protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {processRequest(request, response, "GET");}protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {processRequest(request, response, "POST");}}

result:


6 Sending Request Parameters As XML


(1)postingXML.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>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;//pay attentionvar 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="multiple"><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" onclick="sendPetTypes();" /></form><h2>Server Response:</h2><div id="serverResponse"></div></body></html>

(2)servlet PostingXMLExample.java

package ajax;import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;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;@WebServlet("/PostingXMLExample")public class PostingXMLExample extends HttpServlet {private static final long serialVersionUID = 1L;public PostingXMLExample() {super();}protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {}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 += " " + type;}response.setContentType("text/xml");response.getWriter().println(responseText);}private String readXMLFromRequestBody(HttpServletRequest request) {StringBuffer xml = new StringBuffer();String line = null;try {BufferedReader br = request.getReader();while ((line = br.readLine()) != null) {xml.append(line);}} catch (IOException e) {System.out.println("Error handling XML: " + e.toString());}return xml.toString();}}

result:



7 Sending Data to the Server Using JSON

A JSON object is an unordered set of name/value pairs. The object begins with a { and ends with a }. A colon separates the name/value pairs. 

A JSON array is an ordered collection of values that begins with a [ and ends with a ]. A comma separates the values of the array. 

A value can be a string (enclosed in double quotes), a number, a true or false, an object, or an array. This allows structures to be nested. 



Graphical representation of a JSON object structure (courtesy of www.json.org)


The Web site at www.json.org lists at least 14 bindings to other programming languages, meaning no matter what technology you use on the server, you should be able to communi-cate with the browser through JSON.


(1)sonExample.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>JSON Example</title><script type="text/javascript" src="js/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 objectvar 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" onclick="doJSON();" /></form><h2>Server Response:</h2><div id="serverResponse"></div></body></html>

json.js: https://github.com/douglascrockford/JSON-js


(2)servlet JSONExample.java

package ajax;import java.io.BufferedReader;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.json.JSONException;import org.json.JSONObject;@WebServlet("/JSONExample")public class JSONExample extends HttpServlet {private static final long serialVersionUID = 1L;public JSONExample() {super();}protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {}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 JavaJSONObject jsonObject = null;String responseText = null;try {jsonObject = new JSONObject(json);responseText = "You have a " + jsonObject.getInt("year") + " "+ jsonObject.getString("make") + " "+ jsonObject.getString("model") + " " + "that is "+ jsonObject.getString("color") + " in color.";} catch (JSONException e) {e.printStackTrace();}response.setContentType("text/xml");response.getWriter().println(responseText);}private String readJSONStringFromRequestBody(HttpServletRequest request) {StringBuffer json = new StringBuffer();String line = null;try {BufferedReader br = request.getReader();while ((line = br.readLine()) != null) {json.append(line);}} catch (IOException e) {System.out.println("Error reading JSON string: " + e.toString());}return json.toString();}}

org.json:http://mvnrepository.com/artifact/org.json/json/ 


result:






原创粉丝点击