本章提供了AJAX操作過程步驟的清晰流程。
• 發(fā)生客戶端事件。
• 創(chuàng)建XMLHttpRequest對象。
• XMLHttpRequest對象創(chuàng)建成功并配置。
• XMLHttpRequest對象向Web服務(wù)器發(fā)出異步請求。
• Web服務(wù)器返回包含XML文檔的結(jié)果。
• XMLHttpRequest對象調(diào)用callback()函數(shù)并處理結(jié)果。
• HTML DOM已更新。
下面我們進一步了解這些步驟。
• JavaScript函數(shù)作為事件的結(jié)果被調(diào)用。
• 示例 :JavaScript validateUserId()函數(shù)被映射為輸入表單字段上的onkeyup事件的事件處理程序,其id設(shè)置為“userid”
<input type = "text" size = "20" id = "userid" name = "id" onkeyup = "validateUserId();">.
2.XMLHttpRequest對象創(chuàng)建
var ajaxRequest; // The variable that makes Ajax possible!
function ajaxFunction() {
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
}
3.XMLHttpRequest對象配置
在這一步中,我們將編寫一個將由客戶端事件觸發(fā)的函數(shù),并將注冊一個回調(diào)函數(shù)processRequest()。
function validateUserId() {
ajaxFunction();
// Here processRequest() is the callback function.
ajaxRequest.onreadystatechange = processRequest;
if (!target) target = document.getElementById("userid");
var url = "validate?id=" + escape(target.value);
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}
4,向Web服務(wù)器進行異步請求
源代碼可在下面的代碼中找到。最后幾行代碼是負責向Web服務(wù)器發(fā)出請求。這都是使用XMLHttpRequest對象ajaxRequest完成的。
function validateUserId() {
ajaxFunction();
// Here processRequest() is the callback function.
ajaxRequest.onreadystatechange = processRequest;
if (!target) target = document.getElementById("userid");
var url = "validate?id=" + escape(target.value);
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
}
假設(shè)在用戶ID框中輸入Maxsu,然后在上述請求中,URL設(shè)置為“validate?id=Maxsu”。
可以使用任何語言實現(xiàn)服務(wù)器端腳本,但其邏輯應(yīng)如下所示。
• 獲取客戶端請求。
• 解析客戶端的輸入。
• 需要處理獲得輸入值。
• 將輸出發(fā)送到客戶端。
我們假設(shè)要使用servlet編寫上面的邏輯,那么代碼過程如下:
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
String targetId = request.getParameter("id");
if ((targetId != null) && !accounts.containsKey(targetId.trim())) {
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("<valid>true</valid>");
} else {
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("<valid>false</valid>");
}
}
6.回調(diào)函數(shù)調(diào)用processRequest()
XMLHttpRequest對象配置為在XMLHttpRequest對象的readyState狀態(tài)更改時調(diào)用processRequest()函數(shù)?,F(xiàn)在,此函數(shù)將從服務(wù)器接收結(jié)果,并將執(zhí)行所需的處理。如下例所示,它根據(jù)Webserver返回的值設(shè)置變量消息為true或false。
function processRequest() {
if (req.readyState == 4) {
if (req.status == 200) {
var message = ...;
...
}
7.HTML DOM已更新
這是最后一步,在此步驟中,HTML頁面將會更新。它以下列方式發(fā)生:
• JavaScript使用DOM API獲取對頁面中任何元素的引用。
• 獲取元素引用的推薦方法是調(diào)用。
document.getElementById("userIdMessage"),
// where "userIdMessage" is the ID attribute
// of an element appearing in the HTML document
現(xiàn)在可以使用JavaScript來修改元素的屬性; 修改元素的樣式屬性; 或添加,刪除或修改子元素。下面是一個例子(index.html):
<html>
<script type = "text/javascript">
<!--
function setMessageUsingDOM(message) {
var userMessageElement = document.getElementById("userIdMessage");
var messageText;
if (message == "false") {
userMessageElement.style.color = "red";
messageText = "Invalid User Id";
} else {
userMessageElement.style.color = "green";
messageText = "Valid User Id";
}
var messageBody = document.createTextNode(messageText);
// if the messageBody element has been created simple
// replace it otherwise append the new element
if (userMessageElement.childNodes[0]) {
userMessageElement.replaceChild(messageBody, userMessageElement.childNodes[0]);
} else {
userMessageElement.appendChild(messageBody);
}
}
-->
</script>
<body>
<div id = "userIdMessage"><div>
</body>
</html>
如果已經(jīng)理解了上面的幾個步驟,那么你已經(jīng)可以理解并可以使用AJAX了。