ajax的应用

AJAX是Asynchronous JavaScript and XML 的缩写。它并不是一门新的语言或技术,它实际上是几项技术按一定的方式组合在一在同共的协作中发挥各自的作用,它包括:

使用XHTML和CSS标准化呈现;

使用DOM实现动态显示和交互;

使用XML和XSLT进行数据交换与处理;

使用XMLHttpRequest进行异步数据读取;

最后用JavaScript绑定和处理所有数据;

Ajax的工作原理相当于在用户和服务器之间加了一个中间层,使用户操作与服务器响应异步化。这样把以前的一些服务器负担的工作转嫁到客户端,利于客户端闲置的处理能力来处理,减轻服务器和带宽的负担,从而达到节约ISP的空间及带宽租用成本的目的。

我们以两个验证通行证帐号是否存在的例子来讲述AJAX在实际中的应用:

(1)用文本字符串的方式返回服务器的响应来验证网易通行证帐号是否存在;

(2)以XMLDocument对象方式返回响应来验证金山通行证帐号是否存在;

首先,我们需要用JavaScript来创建XMLHttpRequest 类向服务器发送一个HTTP请求, XMLHttpRequest 类首先由Internet Explorer以ActiveX对象引入,被称为XMLHTTP。 后来Mozilla Netscape Safari和其他浏览器也提供了XMLHttpRequest类,不过它们创建XMLHttpRequest类的方法不同。

对于Internet Explorer浏览器,创建XMLHttpRequest 方法如下:
xmlhttp_request = new ActiveXObject("Msxml2.XMLHTTP"); // 5.0
xmlhttp_request = new ActiveXObject("Microsoft.XMLHTTP");
由于在不同Internet Explorer浏览器中XMLHTTP版本可能不一致,为了更好的兼容不同版本的Internet Explorer浏览器,因此我们需要根据不同版本的Internet Explorer浏览器来创建XMLHttpRequest类,上面代码就是根据不同的Internet Explorer浏览器创建XMLHttpRequest类的方法。对于Mozilla Netscape Safari等浏览器,创建XMLHttpRequest 方法如下:
xmlhttp_request = new XMLHttpRequest();
简单流程说明:
1、客户端初始化XMLHttpRequest方法。
2、客户端设置回调处理方法。
3、发送请求,并自动监视请求。
4、当请求完成时获得服务器端数据。
6、调用更新方法来更新客户端数据。 

附:XMLHttpRequest属性及方法参考

属性:onreadystatechange 指定当readyState属性改变时的事件处理句柄 只写
   readyState 返回当前请求的状态 只读
   responseBody 将回应信息正文以unsigned byte数组形式返回 只读
   responseStream 以Ado Stream对象的形式返回响应信息 只读
   responseText 将响应信息作为字符串返回 只读
   responseXML 将响应信息格式化为Xml Document对象并返回 只读
   status 返回当前请求的http状态码 只读
   statusText 返回当前请求的响应行状态 只读
方法:abort 取消当前请求
   getAllResponseHeaders 获取响应的所有http头
   getResponseHeader 从响应信息中获取指定的http头
   open 创建一个新的http请求,并指定此请求的方法、URL以及验证信息(用户名/密码)
   send 发送请求到http服务器并接收回应
   setRequestHeader 单独指定请求的某个http头

当XMLHttpRequest的open方法中的参数为get的时候
  <script language="javascript" type="text/javascript">
  var xmlHttpRequest = null;
  
  function getXMLHttpRequest()
  {
   if(window.XMLHttpRequest)
   {
    return new XMLHttpRequest();
   }
   else if (window.ActiveXObject)
   {
    request = new ActiveXObject("Microsoft.XMLHTTP");
    
    if (!request)
    {
     request = new ActiveXObject("Msxml2.XMLHTTP");
    }
    
    return request;
   }

  }
  
  function selectionChanged()
  {
   var url = "Handler.ashx?index=" + document.getElementById("select").value;
   xmlHttpRequest = getXMLHttpRequest();
   xmlHttpRequest.onreadystatechange = onReadyStateChange;
   xmlHttpRequest.open("GET", url, true);
   xmlHttpRequest.send(null);
  }
  //回调方法
  function onReadyStateChange()
  {
   if (xmlHttpRequest.readyState == 4)
   {
    if (xmlHttpRequest.status == 200)
    {
     document.getElementById("text").innerHTML =
      xmlHttpRequest.responseXML.documentElement.firstChild.nodeValue;
    }
   }
  }
    </script>
处理页面Handler.ashx
<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler {

    private static readonly string[] TextArray = new string[] {
  "Please select...",
  "Step 1: Construct an XMLHttpRequest object.",
  "Step 2: Set the onreadystatechange event listener.",
  "Step 3: Open the request and send nothing."};

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/xml";

        int index = Int32.Parse(context.Request.QueryString["index"]);

        context.Response.Write("<text>" + TextArray[index] + "</text>");
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}
当XMLHttpRequest的open方法中的参数为post的时候
<%@ Page Language="C#" AutoEventWireup="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Lesson 1 - Demo 3 - Use POST and responseText</title>
    <script language="javascript" type="text/javascript">
  var xmlHttpRequest = null;
  function getXMLHttpRequest()
  {
   if(window.XMLHttpRequest)
   {
    return new XMLHttpRequest();
   }
   else if (window.ActiveXObject)
   {
    request = new ActiveXObject("Microsoft.XMLHTTP");
    
    if (!request)
    {
     request = new ActiveXObject("Msxml2.XMLHTTP");
    }
    
    return request;
   }

  }
  function selectionChanged()
  {
   var url = "PostHandler.ashx";
   xmlHttpRequest=getXMLHttpRequest();
   xmlHttpRequest.open("POST", url, true);
   
   xmlHttpRequest.onreadystatechange = onReadyStateChange;
   xmlHttpRequest.setRequestHeader(
    "Content-Type",
    "application/x-www-form-urlencoded; charset=UTF-8");
   xmlHttpRequest.send("index=" +
    document.getElementById("select").value);
  }  
  function onReadyStateChange()
  {
   if (xmlHttpRequest.readyState == 4)
   {
    if (xmlHttpRequest.status == 200)
    {
     document.getElementById("text").innerHTML =
      xmlHttpRequest.responseText;
    }
   }
  }
    </script>
</head>
<body style="font-family:Verdana; font-size:13px;">
    <form id="form1" runat="server" enctype="application/x-www-form-urlencoded">
  <div>
   <select id="select" onchange="selectionChanged()">
    <option value="0">Please select...</option>
    <option value="1">Step 1</option>
    <option value="2">Step 2</option>
    <option value="3">Step 3</option>
    <option value="4">Step 4</option>
    <option value="5">Step 5</option>
    <option value="6">Step 6</option>
   </select>
  </div>
  <br />
  <div>
   <b>Text:</b>
   <span id="text">Please select...</span>
  </div>
    </form>
</body>
</html>
处理页面Handler.ashx
<%@ WebHandler Language="C#" Class="PostHandler" %>
using System;
using System.Web;

public class PostHandler : IHttpHandler {

 private static readonly string[] TextArray = new string[] {
  "Please select...",
  "Step 1: Create a callback function using requestText",
  "Step 2: Construct an XMLHttpRequest object.",
  "Step 3: Set the onreadystatechange event listener.",
  "Step 4: Open the request using POST method.",
  "Step 5: Set header 'Content-Type' = 'application/x-www-form-urlencoded;'.",
  "Step 6: Send the request body."};
 
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";

  int index = Int32.Parse(context.Request.Params["index"]);

        context.Response.Write(TextArray[index]);
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

 


 

posted on 2008-06-23 20:05  小顾问  阅读(246)  评论(0编辑  收藏  举报