1.處理服務器響應
XMLHttpRequest對象提供了兩個可以用來訪問服務器響應的屬性。第一個屬性responseText將響應提供了一個串,第二個屬性responseXML將響應提供了一個XML對象。
1.1 利用innerHTML屬性創建動態內容
innerHTML.xml 文件內容如下:
<?xml version="1.0" encoding="utf-8" ?> <table border="1"> <tbody> <tr> <th>姓名</th> <th>性別</th> <th>年齡</th> </tr> <tr> <td>小明</td> <td>男</td> <td>12</td> </tr> <tr> <td>小紅</td> <td>女</td> <td>13</td> </tr> <tr> <td>小強</td> <td>男</td> <td>13</td> </tr> </tbody> </table>
innerHTML.htm文件內容如下:
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></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="加載" onclick="startRequest();" /> <div id="results"> </div> </form> </body> </html>
運行效果如下:
點擊按鈕后:
1.2 將響應解析為XML
City.xml文件內容如下:
<?xml version="1.0" encoding="utf-8" ?> <省> <山東> <市> 濟南 </市> <市> 青島 </市> </山東> <北京> <市> 北京市 </市> </北京> </省>
City.HTML文件內容如下:
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></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", "City.xml", true); xmlHttp.send(null); } function handleStateChange() { if (xmlHttp.readyState == 4) { if (xmlHttp.status == 200) { if (requestType == "山東") { listShangDong(); } else if (requestType == "所有") { listAllCity(); } } } } function listShangDong() { var xmlDoc = xmlHttp.responseXML; var node = xmlDoc.getElementsByTagName("山東")[0]; var out = "山東省"; var city = node.getElementsByTagName("市"); outputList("山東省", city); } function listAllCity() { var xmlDoc = xmlHttp.responseXML; var city = xmlDoc.getElementsByTagName("市"); outputList("所有市", city); } 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> <form> <input type="button" value="山東省" onclick="startRequest('山東');" /> <input type="button" value="所有市" onclick="startRequest('所有');" /> </form> </body> </html>
運行效果如下:
1.3 動態編輯網頁
Book.XML文件內容如下:
<?xml version="1.0" encoding="utf-8" ?> <書架> <書> <書名> Ajax基礎教程 </書名> <出版社> 人民郵電出版社 </出版社> <價格> 35.00 </價格> </書> <書> <書名> Programming ASP.NET(中文版) </書名> <出版社> 電子工業出版社 </出版社> <價格> 99.00 </價格> </書> </書架>
Book.htm文件如下:
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></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", "Book.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 book = null; var name = ""; var press = ""; var price = ""; var books = results.getElementsByTagName("書"); for (var i = 0; i < books.length; i++) { book = books[i]; name = book.getElementsByTagName("書名")[0].firstChild.nodeValue; press = book.getElementsByTagName("出版社")[0].firstChild.nodeValue; price = book.getElementsByTagName("價格")[0].firstChild.nodeValue; addTableRow(name, press, price); } var header = document.createElement("h2"); var headerText = document.createTextNode("Results:"); header.appendChild(headerText); document.getElementById("header").appendChild(header); document.getElementById("resultsTable").setAttribute("border", "2"); } function addTableRow(name, press, price) { var row = document.createElement("tr"); var cell = createCellWithText(name); row.appendChild(cell); cell = createCellWithText(press); row.appendChild(cell); cell = createCellWithText(price); 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> <form action="#"> <input type="button" value="搜索" onclick="startRequest();" /> </form> <span id="header"></span> <table id="resultsTable" width="75%" border="0'"> <tbody id="resultsBody"> </tbody> </table> </body> </html>
運行效果如下:
2. 發送參數
GET方法把值作為名/值對放在請求URL中傳遞。資源URL的最后有一個問號(?),問號后面是名/值對。名/值對采用name=value的形式,各個名/值對之間用於號(&)分隔。
POST方法向服務器發送命令參數時,與采用GET方法幾乎是一樣的。類似於GET方法,POST方法會把參數編碼為名/值對,形式為name=value,每個名/值對之間也用與號(&)分隔。這兩種方法的主要區別在於,POST方法將參數串放在請求體中發送,而GET方法時將參數追加到URL中發送。
HTML文件內容:
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></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 name = document.getElementById("name").value; var birthday = document.getElementById("birthday").value; var queryString = "name=" + name + "&birthday=" + birthday; return queryString; } function doRequestUsingGet() { createXMLHttpRequest(); var queryString = "WS.asmx/GetAndPostExample?"; queryString = queryString + createQueryString() + "&timeStamp=" + new Date().getTime(); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.open("GET", queryString, true); xmlHttp.send(null); } function doRequestUsingPOST() { createXMLHttpRequest(); var url = "WS.asmx/GetAndPostExample?timeStamp=" + new Date().getTime(); var queryString = createQueryString(); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.open("POST", url, true); xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-rulencoded;"); xmlHttp.send(queryString); } function handleStateChange() { if (xmlHttp.readyState == 4) { if (xmlHttp.status == 200) { pareseResults(); } } } function pareseResults() { 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> 請輸入姓名和生日</h1> <table> <tbody> <tr> <td> 姓名: </td> <td> <input type="text" id="name" /> </td> </tr> <tr> <td> 生日: </td> <td> <input type="text" id="birthday" /> </td> </tr> </tbody> </table> <form action="#"> <input type="button" value="Get" onclick="doRequestUsingGet();" /> <input type="button" value="Post" onclick="doRequestUsingPOST();" /> <h2> 返回:</h2> <div id="serverResponse"> </div> </form> </body> </html>
后台使用.net寫的webserive,發布后遠行,文件名為WS.asmx
[WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. [System.Web.Script.Services.ScriptService] public class WS : System.Web.Services.WebService { [WebMethod] public string GetAndPostExample() { Context.Response.ContentType = "text/xml"; string results = ""; if (Context.Request.RequestType == "GET") { results += "姓名:" + Context.Request.Params["name"]; results += "生日:" + Context.Request.Params["birthday"]; } else { byte[] input = Context.Request.BinaryRead(Context.Request.TotalBytes); string source = Encoding.UTF8.GetString(input); string[] sources = source.Split(new char[] { '=', '&' }); for (int i = 0; i < sources.Length; i++) { if (sources[i] == "name") { results += "姓名:" + sources[i + 1]; } if (sources[i] == "birthday") { results += "生日:" + sources[i + 1]; } } } results += "時間:" + Context.Request.Params["timeStamp"]; results += "方式:" + Context.Request.RequestType; return results; } }
注意綠色字體部分,需要取消這行的注釋,上面的webservice實現有點復雜,可能有較為簡單的方法。
運行效果如下:
3.使用JSON向服務器發送數據
JSON建立在兩種數據結構基礎上:
1.名/值對集合。在當前編程語言中,這實現了一個對象、記錄或字典
2.值的有序表,這通常實現為一個數組
JSON對象是名/值對的無序集合。對象以{開始,以}結束,名/值用冒號分隔。JSON數組是一個有序的值的集合,以[開始,以]結束,數組中的值用逗號分隔。
JSONExample.htm文件
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></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 doJOSN() { var car = getCarObject(); var carAsJSON = JSON.stringify(car); createXMLHttpRequest(); var url = "WS.asmx/JSONExample?timeStamp=" + new Date().getTime(); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.open("POST", url, true); xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-rulencoded;"); xmlHttp.send(carAsJSON) } function handleStateChange() { if (xmlHttp.readyState == 4) { if (xmlHttp.status == 200) { pareseResults(); } } } function pareseResults() { 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> <form action="#"> <input type="button" value="JSON數據" onclick="doJOSN() ;" /> </form> <h2> 返回:</h2> <div id="serverResponse"> </div> </body> </html>
WS.asmx文件中
[WebMethod] public string JSONExample() { byte[] input = Context.Request.BinaryRead(Context.Request.TotalBytes); string source = Encoding.UTF8.GetString(input); return source; }
效果: