您的位置:首页 > 其它

Ajax基础教程--区分浏览器调用对象

2012-12-17 18:08 357 查看
var xmlHttp;

function createXMLHttpRequest() { if (window.ActiveXObject)

{ xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

} else if (window.XMLHttpRequest)

{ xmlHttp = new XMLHttpRequest(); }

}      

可以看到,创建XMLHttpRequest对象相当容易。首先要创建一个全局作用域变量xmlHttp来保存这个对象的引用。createXMLHttpRequest方法完成创建XMLHttpRequest实例的具体工作。

                            标准的XMLHTTPRequest 操作

abort()                                    停止当前请求

getAllResponseHeaders()                      把HTTP的请求的所有响应首部作为键 /值对返回

getResponseHeader("header")                   返回指定的首部串值

open("method", "url")          建立服务器的调用。method参数可以是GET、POST或PUT。url参数可以是相对的URL或绝对的URL。还包括3个可选参数

send(content)                                向服务器发送请求

setRequestHeader("header", "value")           把指定首部设置为所提供的值。在设置任何首部之前必须先调用open( )

                             标准XMLHttpRequest属性

onreadystatechange              每个状态改变时都会触发这个事件处理器,通常会调用一个JavaScript函数

readyState                    请求状态。有5个可取值:0 = 未始化,1 = 正在加载,2 =已加载, 3 =交互中, 4 = 完成

responseText                        服务器的响应,表示为一个串

responseXML                        服务器的响应,表示为XML。这个对象可以解析为一个DOM对象

status                                    服务器的HTTP状态码(200对应OK,404对应Not Found(未找到) 等)

statusText                             HTTP状态码的相应文本(OK或Not Found(未找到)等)

 

<input type="text"d="email" name="email" onblur="validateEmail()";>

创建XMLHttpRequest对象实例。使用open()方法建立调用,并设置URL及所希望的HTTP方法(通常是GET或POST)。请求实际上通过一个send()方法调用触发。

可能的代码示例  var xmlHttp;

function validateEmail() {

var email = document.getElementById("email");

var url = "validate?email=" + escape(email.value);

if (window.ActiveXObject) {

xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

} else if (window.XMLHttpRequest) {

 xmlHttp = new XMLHttpRequest();

}

xmlHttp.open("GET", url);

xmlHttp.onreadystatechange = callback;

xmlHttp.send(null);

}

是浏览器不会在本地缓存结果,可用下面代码

response.setHeader("Cache-Control", "no-cache");

response.setHeader("Pragma", "no-cache");

上面示例中,XMLHttpRequest对象配置为处理返回时要调用callback ()函数。这个函数会检查XMLHttpRequest属性,然后查看服务器返回状态码。

function callback() {

if (xmlHttp.readyState == 4) {

      if (xmlHttp.status == 200) { //do something interesting here }

      }

}

 

2.5远程脚本

iframe.html

<html>

       <head>

               <title>Example of remote scripting in an IFRAME</title>

        </head>

         <script type="text/javascript">

         function handleResponse() {

                  alert('this function is called from server.html');

            }

           </script>

           <body>

<h1>Remote Scripting with an IFRAME</h1>

<iframe id="beforexhr" name="beforexhr" style="width:0px; height:0px; border: 0px"

src="blank.html"></iframe>

 <a href="server.html" target="beforexhr">call the server</a>

</body>

</html>

 

代码清单2-3 server.html文件

<html>

        <head>

                  <title>the server</title>

         </head>

         <script type="text/javascript">

                   window.parent.handleResponse();

          </script>

          <body>

          </body>

</html>

2.6 发送一个简单地请求

XMLHttpRequest对象发送请求的基本步骤:

1. 为得到XMLHttpRequest对象实例的而一个引用,可以创建一个新的实例,也可以访问包含有XMLHttpRequest实例的一个变量

2. 告诉XMLHttpRequest对象,哪个函数会处理XMLHttpRequest对象状态的改变,为此要把对象的onreadystatechange属性设置为指向JavaScript函数的指针

3. 指定请求的属性。XMLHttpRequest对象的open()方法会指定将发出的请求。open()方法取3个参数:一个是指示所用方法(通常是GET或POST)的串;一个是表示目标资源URL的串;一个是Boolean值,指示请求是否异步

4. 将请求发送给服务器。XMLHttpRequest对象的send()方法把请求发送到指定的目标资源。send()方法接受一个参数,通常是一个串或一个DOM对象。这个参数作为请求体的一部分发送到目标URL。当向send()方法提供参数时,要确保open()中指定的方法是POST。如果没有数据作为被请求体的一部分被发送,则使用null

你需要XMLHttpRequest对象的一个实例,要告诉它如果状态有变化怎么做,还要告诉他向那里发送请求以及如何发送请求,最后还需要知道XMLHttpRequest发送请求。

 

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>Simple XMLHttpRequest</title>

<script type="text/javascript">

var xmlHttp;

function createXMLHttpRequest() {

         if (window.ActiveXObject) {

                 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

          }

           else if (window.XMLHttpRequest) {

                     xmlHttp = new XMLHttpRequest();

            }

}

function startRequest() {

       createXMLHttpRequest();

        xmlHttp.onreadystatechange = handleStateChange;

        xmlHttp.open("GET", "simpleResponse.xml", true);

        xmlHttp.send(null);

}

function handleStateChange() {

            if(xmlHttp.readyState == 4) {

                     if(xmlHttp.status == 200) {

                                alert("The server replied with: " + xmlHttp.responseText);

                             }

                   }

}

</script>

</head>

<body>

            <form action="#">

                         <input type="button" value="Start Basic Asynchronous Request"    onclick="startRequest();"/>

            </form>

</body>

</html>

服务器的响应文件simpleResponse.xml只有一行文本。点击HTML页面上的按钮会生成一个警告框,其中显示simpleResponse.xml文件内容。

 

 

startRequest函数将回调函数设置为handleStateChange函数;

3. startRequest函数使用open()方法来设置请求方法(GET)及请求目标,并且设置为异步地完成请求

4.使用XMLHttpRequest对象的send()方法发送请求

5. XMLHttpRequest对象的内部状态每次有变时,都会调用handleStateChange函数。一旦接收到响应(如果readyState属性值为4),div元素的innerHTML属性就将使用XMLHttpRequest对象的responseText属性设置

        代码清单显示了innerHTML.html。代码显示了innerHTML.xml,表示搜索生成的内容

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

     <html xmlns="http://www.w3.org/1999/xhtml">

<head>

     <title>Using responseText with innerHTML</title>

<script type="text/javascript">

 var xmlHttp;

 function createXMLHttpRequest() {

       if (window.ActiveXObject) {

                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

         }

         else if (window.XMLHttpRequest) {

                   xmlHttp = new XMLHttpRequest();

          }

}

function startRequest() {

           createXMLHttpRequest();

           xmlHttp.onreadystatechange = handleStateChange;

           xmlHttp.open("GET", "innerHTML.xml", true);

           xmlHttp.send(null);

}

function handleStateChange() {

          if(xmlHttp.readyState == 4) {

                 if(xmlHttp.status == 200) {

                         document.getElementById("results").innerHTML = xmlHttp.responseText;

                    }

            }

}

</script>

</head>

<body>

          <form action="#">

                   <input type="button" value="Search for Today's Activities"  onclick="startRequest();"/>

            </form>

            <div id="results">

            </div>

</body>

</html>

 

                   innerHTML.xml代码
<table border="1">

       <tbody>

              <tr>

                     <th>Activity Name</th>

                     <th>Location</th>

                     <th>Time</th>

               </tr>

               <tr>

                        <td>Waterskiing</td>

                        <td>Dock #1</td>

                        <td>9:00 AM</td>

                </tr>

                <tr>

                          <td>Volleyball</td>

                          <td>East Court</td>

                          <td>2:00 PM</td>

                  </tr>

                  <tr>

                          <td>Hiking</td>

                          <td>Trail 3</td>

                          <td>3:30 PM</td>

                    </tr>

</tbody>

</table>

 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: