`
可执行
  • 浏览: 16981 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

一个兼容性很好的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 the server
// 创建process()函数,读取服务器上的回显文本
function process()
{
  // only continue if xmlHttp isn't void
  // 当 xmlHttp不为空时继续
  if (xmlHttp)
  {
    // try to connect to the server
         //尝试连接服务器
    try
    {
      // initiate reading the async.txt file from the server
           //开始读取服务器上的async.txt文件,也可以是http://www.a.com/index.php?app=ajax&act=response
      xmlHttp.open("GET", "async.txt", true);      //在这里只是设置,发送。设置get方法提交的request参数,像是在地址栏中输入http://async.txt,调用方法用异步(或者解释成设置异步读取的文件async.txt)
      xmlHttp.onreadystatechange = handleRequestStateChange; //设置XMLHttpRequest处理状态变化的函数。
      xmlHttp.send(null);     //把以上设置发送到服务器,get方法直接在以上的open方法设置提交参数,如果为post,设置send(app=ajax&act=response)
    }
    // display the error in case of failure
         //如果出现异常,显示错误信息
    catch (e)
    {
      alert("Can't connect to server:\n" + e.toString());
    }
  }
}
// function that handles the HTTP response
//处理http响应的函数
function handleRequestStateChange()
{
  // obtain a reference to the <div> element on the page
  //获取页面上<div>元素的id
  myDiv = document.getElementById("myDivElement");
  // display the status of the request
  //依次显示请求状态信息
  if (xmlHttp.readyState == 1)
  {
    myDiv.innerHTML += "Request status: 1 (loading) <br/>";
  }
  else if (xmlHttp.readyState == 2)
  {
    myDiv.innerHTML += "Request status: 2 (loaded) <br/>";
  }
  else if (xmlHttp.readyState == 3)
  {
    myDiv.innerHTML += "Request status: 3 (interactive) <br/>";
  }
  // when readyState is 4, we also read the server response
  //当转换到状态4时,读取服务器的响应
  else if (xmlHttp.readyState == 4)
  {
    // continue only if HTTP status is "OK"
         //  xmlHttp.status为200时表示处理成功
    if (xmlHttp.status == 200)
    {
      try
      {
        // read the message from the server
                   //读取服务器信息
        response = xmlHttp.responseText;
        // display the message
                   //显示信息到指定id
        myDiv.innerHTML +=  "Request status: 4 (complete). Server said said: <br/>";
        myDiv.innerHTML += response;
      }
      catch(e)
      {
        // display error message
        alert("Error reading the response: " + e.toString());
      }
    }
    else
    {
      // display status message
      alert("There was a problem retrieving the data:\n" +
            xmlHttp.statusText);
    }
  }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics