现在的位置: 首页 > 综合 > 正文

ajax 与XMLHttpRequest对象(1/4)

2014年09月05日 ⁄ 综合 ⁄ 共 2166字 ⁄ 字号 评论关闭
    使用XMLHttpRequest对象发送请求的基本步骤如下:

  • 创建一个XMLHttpRequest的引用
  • 告诉XMLHttpRequest对象,哪个函数会处理XMLHttpRequest对象状态的改变,为此要设置onreadystatechange属性
  • 指定请求的属性。open()
  • 将请求发送给服务器。send()
  • xmlHttp.responseText将响应提供为一个串

以下示例代码包括两个文件,分别为:
simpleRequest.html和simpleResponse.xml

以下为其完整代码:

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  2. <html>
  3.   <head>
  4.     <title>simpleRequest.html</title>
  5.      <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  6.    </head>
  7.   <script type="text/javascript" >
  8.     var xmlHttp;
  9.    //创建一个XMLHttpRequest对象
  10.     function createXMLHttpRequest()
  11.     {
  12.       if(window.ActiveXObject)
  13.       {
  14.          xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  15.       }
  16.       else if(window.XMLHttpRequest)
  17.       {
  18.         xmlHttp = new XMLHttpRequest();
  19.       }
  20.     }
  21.     
  22.     //开始一个请求
  23.     function startRequest()
  24.     {
  25.       createXMLHttpRequest();
  26.       xmlHttp.onreadystatechange = handleStateChange;
  27.       xmlHttp.open("GET","simpleResponse.xml",true);
  28.       xmlHttp.send(null);
  29.     }
  30.     
  31.     //当xmlHttp对象的内部状态发生变化时候,调用此处理函数
  32.     //一旦接受到相应(readyState为4)
  33.     function handleStateChange()
  34.     {
  35.       if(xmlHttp.readyState == 4)
  36.       {
  37.          if(xmlHttp.status == 200)
  38.          {
  39.            alert("The server replied with:"+xmlHttp.responseText);
  40.            document.getElementById("result").innerHTML = xmlHttp.responseText;
  41.          }
  42.       }
  43.     }
  44.   </script>
  45.   <body>
  46.      <form>
  47.         <input type="button" value="Start Basic Asynchronous Request" onclick="startRequest();" />
  48.      </form>
  49.      <div id="result" style="boder:1px solid red;width:400px;height:200px;">box</div>
  50.      <hr/>
  51.      <ul>使用XMLHttpRequest对象发送请求的基本步骤如下:
  52.          <li>创建一个XMLHttpRequest的引用</li>
  53.          <li>告诉XMLHttpRequest对象,哪个函数会处理XMLHttpRequest对象状态的改变,为此要设置onreadystatechange属性</li>
  54.          <li>指定请求的属性。open()</li>
  55.          <li>将请求发送给服务器。send()</li>
  56.          <li>xmlHttp.responseText将响应提供为一个串</li>
  57.      </ul>
  58.  </body>
  59. </html>
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <books>
  3.    <book>
  4.       <author>Henry</author>
  5.       <pubdate>2011-11-11</pubdate>
  6.       <Subject>西游记</Subject>
  7.    </book>
  8.     <book>
  9.       <author>Kater</author>
  10.       <pubdate>2015-11-11</pubdate>
  11.       <Subject>娃哈哈</Subject>
  12.    </book>
  13. </books>

效果:当点击页面上的button后,会alert出一个框,其中内容为xml文件中的内容。然后在html页面中id=result的div中显示xml中的信息。

抱歉!评论已关闭.