AJAX - 操作
本章让您清楚地了解AJAX操作的具体步骤。
AJAX操作步骤
- 客户端事件发生。
- 已创建 XMLHttpRequest 对象。
- XMLHttpRequest 对象已配置。
- XMLHttpRequest 对象向 Web 服务器发出异步请求。
- Web服务器返回包含XML文档的结果。
- XMLHttpRequest 对象调用callback() 函数并处理结果。
- HTML DOM 已更新。
让我们一一执行这些步骤。
客户端事件发生
JavaScript 函数作为事件的结果被调用。
示例 − validateUserId() JavaScript 函数作为事件处理程序映射到 ID 设置为 "userid" 的输入表单字段上的 onkeyup 事件
<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 服务器发出异步请求
源代码可以在上面的代码中找到。 以粗体字体编写的代码负责向网络服务器发出请求。 这一切都是使用 XMLHttpRequest 对象 ajaxRequest 完成的。
function validateUserId() { ajaxFunction(); // Here processRequest() is the callback function. ajaxRequest.onreadystatechange = processRequest; <b>if (!target) target = document.getElementById("userid"); var url = "validate?id = " + escape(target.value); ajaxRequest.open("GET", url, true); ajaxRequest.send(null);</b> }
假设您在用户 ID 框中输入 Zara,则在上述请求中,URL 将设置为"validate?id = Zara"。
Web服务器返回包含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() 函数。 现在该函数将从服务器接收结果并进行所需的处理。 如下例所示,它根据 Web 服务器返回的值将变量消息设置为 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 来修改元素的属性; 修改元素的样式属性; 或者添加、删除或修改子元素。 这是一个例子 −
<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>
如果你理解了上述七个步骤,那么你就差不多完成了AJAX。 在下一章中,我们将更详细地了解 XMLHttpRequest 对象。