日期:2014-05-16  浏览次数:20751 次

一个兼容性很好的ajax最小实现
这个模型在本人的开发中已经使用多次表现良好:

async.txt文档

Hello client!

async.html文件

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
  <head>
    <title>AJAX Foundations: Using XMLHttpRequest</title>
    <script type="text/javascript" src="async.js"></script>
  </head>
  <body onload="process()">
    Hello, server!
    <br/>
    <div id="myDivElement" />
  </body>
</html>
async.js文件
// holds an instance of XMLHttpRequest
//建立一个XmlHttpRequestObject对象实例
var xmlHttp = createXmlHttpRequestObject();
// creates an XMLHttpRequest instance
//建立XmlHttpRequestObject对象
function createXmlHttpRequestObject()
{
  // will store the reference to the XMLHttpRequest object
  //用于存储XmlHttpRequest对象的引用
  var xmlHttp;
  // this should work for all browsers except IE6 and older
  //创建除了ie6 或者其更早版本外的所有浏览器
  //(用try catch结构是我见过最好的最具兼容性的创建XMLHttpRequest对象实例的方法)
  try
  {
    // try to create XMLHttpRequest object
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    // assume IE6 or older
         //假设是ie6 或其更早版本
    var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
                                    "MSXML2.XMLHTTP.5.0",
                                    "MSXML2.XMLHTTP.4.0",
                                    "MSXML2.XMLHTTP.3.0",
                                    "MSXML2.XMLHTTP",
                                    "Microsoft.XMLHTTP");
    // try every prog id until one works
         //顺序尝试创建每一个对象,直到成功为止
    for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++)
    {
      try
      {
        // try to create XMLHttpRequest object
                   //尝试创建XMLHttpRequest对象
        xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
      }
      catch (e) {}
    }
  }
  // return the created object or display an error message
  //返回已经创建的对象,或显示错误信息
  //实际应用中这里最好不要把错误信息发送到客户端
  if (!xmlHttp)
    alert("Error creating the XMLHttpRequest object.");
  else
    return xmlHttp;
}
// called to read a file from