Ajax操作
Ajax操作:本节将给你AJAX操作的具体步骤让你清楚地了解。
本节将给你AJAX操作的具体步骤让你清楚地了解.
	AJAX操作的步骤
- 一个客户端事件发生
- 创建一个XMLHttpRequest对象
- XMLHttpRequest对象配置
- XMLHttpRequest对象异步请求到Web服务器.
- Web服务器返回的结果包含XML文档.
- XMLHttpRequest对象调用callback()函数和处理结果。
- HTML DOM更新
让我们逐一采取以下步骤
1. 一个客户端事件发生
- 一个JavaScript函数被称为事件的结果
- 例如:validateUserId()是JavaScript函数被映射为一个事件处理程序上输入表单域的onkeyup事件,其ID设置为“用户ID”
- <input type=”text” size=”20″ id=”userid” name=”id” onkeyup=”validateUserId();”>
2. 创建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;
      }
   }
 }
}
3. 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);
}
4. 使异少请求的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框中mohammad在上述请求的URL,然后设置tovalidate?ID=mohammad
5. 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("true");
   }
   else
   {
      response.setContentType("text/xml");
      response.setHeader("Cache-Control", "no-cache");
      response.getWriter().write("false");
   }
}
6. 被称为回调函数processRequest()
配置XMLHttpRequest对象调用processRequest()函数,当有一个状态变化到XMLHttpRequest对象的readyState。现在,这个函数将收到从服务器的结果,将不所需处理。在下面的例子,它设置一个真或假的变量的消息返回值是从网络服务器上的.
function processRequest() {
   if (req.readyState == 4) {
      if (req.status == 200) {
         var message = ...;
...
}
7. 更新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对象.



