本章提供了AJAX操作過程步驟的清晰流程。
AJAX操作的步驟
- 發生客戶端事件。
- 創建XMLHttpRequest對象。
- XMLHttpRequest對象創建成功並配置。
- XMLHttpRequest對象向Web伺服器發出非同步請求。
- Web伺服器返回包含XML文檔的結果。
- XMLHttpRequest對象調用
callback()
函數並處理結果。 - HTML DOM已更新。
下麵我們進一步瞭解這些步驟。
發生客戶端事件
- JavaScript函數作為事件的結果被調用。
- 示例 - JavaScript validateUserId()函數被映射為輸入表單字段上的onkeyup事件的事件處理程式,其
id
設置為“userid” <input type = "text" size = "20" id = "userid" name = "id" onkeyup = "validateUserId();">.
XMLHttpRequest對象創建
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;
}
}
}
}
XMLHttpRequest對象配置
在這一步中,我們將編寫一個將由客戶端事件觸發的函數,並將註冊一個回調函數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);
}
向Web伺服器進行非同步請求
源代碼可在下面的代碼中找到。最後幾行代碼是負責向Web伺服器發出請求。這都是使用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);
}
假設在用戶ID框中輸入Maxsu
,然後在上述請求中,URL設置為“validate?id=Maxsu”。
Webserver返回包含XML文檔的結果
可以使用任何語言實現伺服器端腳本,但其邏輯應如下所示。
- 獲取客戶端請求。
- 解析客戶端的輸入。
- 需要處理獲得輸入值。
- 將輸出發送到客戶端。
我們假設要使用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>");
}
}
回調函數調用processRequest()
XMLHttpRequest對象配置為在XMLHttpRequest對象的readyState
狀態更改時調用processRequest()
函數。現在,此函數將從伺服器接收結果,並將執行所需的處理。如下例所示,它根據Webserver返回的值設置變數消息為true
或false
。
function processRequest() {
if (req.readyState == 4) {
if (req.status == 200) {
var message = ...;
...
}
HTML DOM已更新
這是最後一步,在此步驟中,HTML頁面將會更新。它以下列方式發生 -
- JavaScript使用DOM API獲取對頁面中任何元素的引用。
- 獲取元素引用的推薦方法是調用。
document.getElementById("userIdMessage"),
// where "userIdMessage" is the ID attribute
// of an element appearing in the HTML document
現在可以使用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>
如果已經理解了上面的幾個步驟,那麼你已經可以理解並可以使用AJAX了。
上一篇:
AJAX流覽器支持
下一篇:
AJAX+PHP資料庫操作