XMLHttpRequest 对象提供了在网页加载后与服务器进行通信的方法。

XMLHttpRequest 对象是开发者的梦想,因为您能够:

  • 在不重新加载页面的情况下更新网页
  • 在页面已加载后从服务器请求数据
  • 在页面已加载后从服务器接收数据
  • 在后台向服务器发送数据

    所有现代的浏览器都支持 XMLHttpRequest 对象。

     

    1. 创建 XMLHttpRequest 对象

    通过一行简单的 JavaScript 代码,我们就可以创建 XMLHttpRequest 对象。

    在所有现代浏览器中(包括 IE 7):

    XML HTTPRequest对象xmlhttp=new XMLHttpRequest()

     在 Internet Explorer 5 和 6 中:

    XML HTTPRequest对象xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")

     

    实例

     loadXMLDoc(url)
    {
    xmlhttp=null;
    if (window.XMLHttpRequest)
      {
    // code for all new browsers
      xmlhttp=new XMLHttpRequest();
      }
    else if (window.ActiveXObject)
      {
    // code for IE5 and IE6
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    if (xmlhttp!=null)
      {
      xmlhttp.onreadystatechange
    =state_Change;
      xmlhttp.open(
    "GET",url,true);
      xmlhttp.send(
    null);
      }
    else
      {
      alert(
    "Your browser does not support XMLHTTP.");
      }
    }

    function state_Change()
    {
    if (xmlhttp.readyState==4)
      {
    // 4 = "loaded"
      if (xmlhttp.status==200)
        {
    // 200 = OK
        // XML HTTPRequest对象our code hereXML HTTPRequest对象
        }
      
    else
        {
        alert(
    "Problem retrieving XML data");
        }
      }
    }
    </script>

    注释:onreadystatechange 是一个事件句柄。它的值 (state_Change) 是一个函数的名称,当 XMLHttpRequest 对象的状态发生改变时,会触发此函数。状态从 0 (uninitialized) 到 4 (complete) 进行变化。仅在状态为 4 时,我们才执行代码。

     

     为什么使用 Async=true ?

    我们的实例在 open() 的第三个参数中使用了 "true"。

    该参数规定请求是否异步处理。

    True 表示脚本会在 send() 方法之后继续执行,而不等待来自服务器的响应。

    onreadystatechange 事件使代码复杂化了。但是这是在没有得到服务器响应的情况下,防止代码停止的最安全的方法。

    通过把该参数设置为 "false",可以省去额外的 onreadystatechange 代码。如果在请求失败时是否执行其余的代码无关紧要,那么可以使用这个参数。

     

     更多实例:

     1) 当键入文本时与服务器进行 XML HTTP 通信



    xmlHttp=null;

    function showHint(str)
    {
    if (str.length==0)
      { 
      document.getElementById(
    "txtHint").innerHTML="";
      
    return;
      }
    try
      {
    // Firefox, Opera 8.0+, Safari, IE7
      xmlHttp=new XMLHttpRequest();
      }
    catch(e)
      {
    // Old IE
      try
        {
        xmlHttp
    =new ActiveXObject("Microsoft.XMLHTTP");
        }
      
    catch(e)
        {
        alert (
    "Your browser does not support XMLHTTP!");
        
    return;  
        }
      }
    url
    ="/ajax/gethint.asp?q=" + str;
    url
    =url+"&sid="+Math.random();
    xmlHttp.open(
    "GET",url,false);
    xmlHttp.send(
    null);
    document.getElementById(
    "txtHint").innerHTML=xmlHttp.responseText;
    }
    </script> 
    </head>
    <body><form> 
    First Name:
    <input type="text" id="txt1"
    onkeyup
    ="showHint(this.value)">
    </form><p>Suggestions: <span id="txtHint"></span></p> </body>
    </html>

     2)  通过 XML HTTP 把一个 textfile 载入一个 div 元素中

     loadXMLDoc(url)
    {
    xmlhttp=null;
    if (window.XMLHttpRequest)
      {
    // code for Firefox, Opera, IE7, etc.
      xmlhttp=new XMLHttpRequest();
      }
    else if (window.ActiveXObject)
      {
    // code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    if (xmlhttp!=null)
      {
      xmlhttp.onreadystatechange
    =state_Change;
      xmlhttp.open(
    "GET",url,true);
      xmlhttp.send(
    null);
      }
    else
      {
      alert(
    "Your browser does not support XMLHTTP.");
      }
    }

    function state_Change()
    {
    if (xmlhttp.readyState==4)
      {
    // 4 = "loaded"
      if (xmlhttp.status==200)
        {
    // 200 = "OK"
        document.getElementById('T1').innerHTML=xmlhttp.responseText;
        }
      
    else
        {
        alert(
    "Problem retrieving data:" + xmlhttp.statusText);
        }
      }
    }
    </script>
    </head>

    <body onload="loadXMLDoc('/example/xdom/test_xmlhttp.txt')">
    <div id="T1" style="border:1px solid black;height:40;width:300;padding:5"></div><br />
    <button onclick="loadXMLDoc('/example/xdom/test_xmlhttp2.txt')">Click</button>
    </body>

    </html>

     3)  通过 XML HTTP 进行 HEAD 请求

     loadXMLDoc(url)
    {
    xmlhttp=null;
    if (window.XMLHttpRequest)
      {
    // code for Firefox, Mozilla, IE7, etc.
      xmlhttp=new XMLHttpRequest();
      }
    else if (window.ActiveXObject)
      {
    // code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    if (xmlhttp!=null)
      {
      xmlhttp.onreadystatechange
    =state_Change;
      xmlhttp.open(
    "GET",url,true);
      xmlhttp.send(
    null);
      }
    else
      {
      alert(
    "Your browser does not support XMLHTTP.");
      }
    }

    function state_Change()
    {
    if (xmlhttp.readyState==4)
      {
    // 4 = "loaded"
      if (xmlhttp.status==200)
        {
    // 200 = "OK"
        document.getElementById('p1').innerHTML=xmlhttp.getAllResponseHeaders();
        }
      
    else
        {
        alert(
    "Problem retrieving data:" + xmlhttp.statusText);
        }
      }
    }
    </script>
    </head>
    <body>

    <id="p1">
    The getAllResponseHeaders() function returns the headers of a resource.
    The headers contain file information like length,
    server-type, content-type, date-modified, etc.
    </p>

    <button onclick="loadXMLDoc('/example/xdom/test_xmlhttp.txt')">Get Headers</button>

    </body>
    </html>

     4)  通过 XML HTTP 进行指定的 HEAD 请求

     loadXMLDoc(url)
    {
    xmlhttp=null;
    if (window.XMLHttpRequest)
      {
    // all modern browsers
      xmlhttp=new XMLHttpRequest();
      }
    else if (window.ActiveXObject)
      {
    // for IE5, IE6
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    if (xmlhttp!=null)
      {
      xmlhttp.onreadystatechange
    =state_Change;
      xmlhttp.open(
    "GET",url,true);
      xmlhttp.send(
    null);
      }
    else
      {
      alert(
    "Your browser does not support XMLHTTP.");
      }
    }

    function state_Change()
    {
    if (xmlhttp.readyState==4)
      {
    // 4 = "loaded"
      if (xmlhttp.status==200)
        {
    // 200 = "OK"
        document.getElementById('p1').innerHTML="This file was last modified on: " + xmlhttp.getResponseHeader('Last-Modified');
        }
      
    else
        {
        alert(
    "Problem retrieving data:" + xmlhttp.statusText);
        }
      }
    }
    </script>
    </head>
    <body>

    <id="p1">
    The getResponseHeader() function returns a header from a resource.
    Headers contain file information like length,
    server-type, content-type, date-modified, etc.
    </p>

    <button onclick="loadXMLDoc('/example/xdom/test_xmlhttp.txt')">Get "Last-Modified"</button>

    </body>
    </html>

     5)  通过 XML HTTP 列出 XML 文件中的数据

     loadXMLDoc(url)
    {
    xmlhttp=null;
    if (window.XMLHttpRequest)
      {
    // code for IE7, Firefox, Mozilla, etc.
      xmlhttp=new XMLHttpRequest();
      }
    else if (window.ActiveXObject)
      {
    // code for IE5, IE6
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    if (xmlhttp!=null)
      {
      xmlhttp.onreadystatechange
    =onResponse;
      xmlhttp.open(
    "GET",url,true);
      xmlhttp.send(
    null);
      }
    else
      {
      alert(
    "Your browser does not support XMLHTTP.");
      }
    }

    function onResponse()
    {
    if(xmlhttp.readyState!=4return;
    if(xmlhttp.status!=200)
      {
      alert(
    "Problem retrieving XML data");
      
    return;
      }

    txt
    ="<table border='1'>";
    x
    =xmlhttp.responseXML.documentElement.getElementsByTagName("CD");
    for (i=0;i<x.length;i++)
      {
      txt
    =txt + "<tr>";
      xx
    =x[i].getElementsByTagName("TITLE");
        {
        
    try
          {
          txt
    =txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
          }
        
    catch (er)
          {
          txt
    =txt + "<td> </td>";
          }
        }
      xx
    =x[i].getElementsByTagName("ARTIST");
        {
        
    try
          {
          txt
    =txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
          }
        
    catch (er)
          {
          txt
    =txt + "<td> </td>";
          }
        }
      txt
    =txt + "</tr>";
      }
    txt
    =txt + "</table>";
    document.getElementById(
    'copy').innerHTML=txt;
    }

    </script>
    </head>

    <body>
    <div id="copy">
    <button onclick="loadXMLDoc('/example/xdom/cd_catalog.xml')">Get CD info</button>
    </div>
    </body>
    </html>

     

    2. XML / ASP

    您也可以把 XML 文档打开并发送到服务器上的 ASP 页面,分析此请求,然后传回结果。


    xmlHttp=null;
    if (window.XMLHttpRequest)
      {
    // code for IE7, Firefox, Opera, etc.
      xmlHttp=new XMLHttpRequest();
      }
    else if (window.ActiveXObject)
      {
    // code for IE6, IE5
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    if (xmlHttp!=null)
      {
      xmlHttp.open(
    "GET""note.xml"false);
      xmlHttp.send(
    null);
      xmlDoc
    =xmlHttp.responseText;

      xmlHttp.open(
    "POST""demo_dom_http.asp"false);
      xmlHttp.send(xmlDoc);
      document.write(xmlHttp.responseText);
      }
    else
      {
      alert(
    "Your browser does not support XMLHTTP.");
      }
    </script>
    </body>
    </html>

     

    ASP 页面,由 VBScript 编写:

    XML HTTPRequest对象<%
    XML HTTPRequest对象
    set xmldoc = Server.CreateObject("Microsoft.XMLDOM")
    XML HTTPRequest对象xmldoc.async
    =false
    XML HTTPRequest对象xmldoc.load(request)
    XML HTTPRequest对象
    XML HTTPRequest对象
    for each x in xmldoc.documentElement.childNodes
    XML HTTPRequest对象   
    if x.NodeName = "to" then name=x.text
    XML HTTPRequest对象
    next
    XML HTTPRequest对象response.write(name)
    XML HTTPRequest对象%
    >

     

    通过使用 response.write 属性把结果传回客户端。

     

     

    相关文章: