Ajax之XMLHttpRequest对象(技术分析篇)

Ajax技术分析篇

Ajax是Asynchronous JavaScript XML的简写。这一技术 能够向服务器请求额外的数据而无须卸载页面。属于异步加载数据。

Ajax技术的核心是 XMLHttpRequest对象,简称XHR,XHR向服务器发送请求和解析服务器响应提供了流畅的接口。能够以异步方式从服务器取得更多的信息,意味着用户单击后,可以不必刷新碳也能够取得新的数据,也就是说可以使用XHR对象取得新的数据,然后通过DOM操作将数据插入到页面中。 这种技术无须刷新页面就可以向服务器发送请求和解析服务器响应



XMLHttpRequest对象

Ajax技术的核心就是XMLHttpRequest对象,可以使用这个对象创建实例,我们先来看一个实例。

首先,web页面的代码为:
<!doctype html>
<html lang="zh-en">
  <head>
    <meta charset="utf-8">
    <title>Ajax学习</title>
    <style>
 
    </style>  
  </head>
  <body>
    

  <script>
     var xhr;
     if (window.XMLHttpRequest) {
         //兼容IE7+, Firefox, Chrome, Opear, Safari浏览器
         xhr = new XMLHttpRequest(); //创建一个XMLHttpRequest对象实例
     } else {
         //兼容IE5, IE6浏览器
         xhr = new ActiveXObject("Microsoft.XMLHTTP");
     }
     xhr.onreadystatechange = function () { //readyStatechange事件 事件处理程序
         if (xhr.readyState == 4 && xhr.status == 200) {
             alert(xhr.responseText);
         }
     }
     xhr.open("GET", "test.php", true);
     xhr.send(); //发送请求
 </script>
  </body>
</html>

接着,服务器端的PHP代码为:

<?php
    echo "hello world!"
?>

注意,这两个文件需放在同一个文件夹下,如均放在名为“ajaxdemo”的文件夹下,在浏览器中输入"localhost:8080/ajaxdemo/index.html"访问。

效果为:


可以看出,弹出一个警告框“hello world!”,正是用PHP写得代码。


下面将介绍XMLHttpRequest对象的属性和方法。


初始化请求open()

使用XMLHttpRequest对象的open()方法来初始化请求,就以上例为例:
xhr.open("GET", "test.php", true);

这里的open()方法传入了三个参数:
get:定义了请求方法为get方法。
test.php:表示请求的目标地址,可以为绝对地址,也可以为相对地址。
treu:表示请求的方式为异步请求,如果为false,表示为同步请求。


new XMLHttpRequest.open()方法可以接收6个参数:
  • method,发送请求的方法,有"get","post","head","put","delete"等,大小写不敏感。
  • url,请求的URL地址,可以是绝对地址,也可以是相对地址。
  • true/false,布尔值,表示是异步请求,还是同步请求。默认为true,表示异步请求,同步请求为false。
  • user,字符串,如果服务器端需要身份验证,在此输入用户名,可带参数。
  • possword,字符串,验证信息中的密码部分,如果用户名为空,则被忽略,可带参数。


设置请求的HTTP头信息

XMLHttpRequest对象提供了setRequestHeader方法来设置请求的头部信息。

格式: new XMLHttpRequest.setRequestHeader(strHeader, strValue);

strHeader:字符串,表示头名称
strValue:字符串,表示值

常用的方法如下:
  • 用post方法提交请求时,设置编码类型:
new XMLHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

  • 提交COOKIE:
new XMLHttpRequest.setRequestHeader("COOKIE", "cookiename=cookievalue");

  • 提交XML:
new XMLHttpRequest.setRequestHeader("Content-Type", "text/xml");


注意,如果已存在命名的HTTP头,则会被新的定义覆盖,这个方法需要在open()方法后面使用。



例如:以提交COOKIE为例:
var xhr;
if (window.XMLHttpRequest) {
    //兼容IE7+, Firefox, Chrome, Opear, Safari浏览器
    xhr = new XMLHttpRequest(); //创建一个XMLHttpRequest对象实例
} else {
    //兼容IE5, IE6浏览器
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
        alert(xhr.responseText);
    }
}    
xhr.open("GET", "test.php", true);
xhr.setRequestHeader("COOKIE", "author=huang"); //该方法需要在open()方法后面使用
xhr.send(); //发送请求

这样就能弹出警告框显示COOKIE的值“huang”。



发送请求send()

在XMLHttpRequest对象被初始化后,就可以使用send()方法发送请求了。

格式: new XMLHttpRequest.send();


如果请求是同步请求即open()的第三个参数是false, send()方法会等 请求完成后或超时后才返回,请求过程中页面会处于'中断"状态,也就是"假死"状态,当请求返回后才继续执行。 如果请求是异步请求,那么就会立即返回,不会处于“中断”状态


当使用“GET”提交请求时,或者没有需要发送的数据时,发送请求可以使用send(null)或者省略send()操作。


下面举例来区分异步请求与同步请求的差异:

<body>
  <input type="button" οnclick="syncRequest();" value="发送同步请求">
  <input type="button" οnclick="asyncRequest();" value="发送异步请求">

<script>
 
    function asyncRequest () {
        var xhr;
        if (window.XMLHttpRequest) {
            //兼容IE7+, Firefox, Chrome, Opear, Safari浏览器
            xhr = new XMLHttpRequest(); //创建一个XMLHttpRequest对象实例
        } else {
            //兼容IE5, IE6浏览器
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                alert(xhr.responseText);
            }
        }    
        xhr.open("GET", "test.php", true);
        xhr.send(); //发送请求
        }
        //同步请求
        function syncRequest () {
            var xhr;
            if (window.XMLHttpReuqest) {
                xhr = new XMLHttpRequest();
            } else {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xhr.open("GET", "test.php", false);
            xhr.send();
            alert(xhr.responseText);
        }
</script>
</body>

当点击同步请求时,页面会出现“假死“状态,而点击异步请求时,会很快地弹出警告框,说明,异步请求比同步请求提供了更好的用户体验。




获取请求的当前状态readyState

一个XMLHttpRequest对象在其周期中有5种状态,分别为:
  • 0(未初始化):对象已经创建,但是未调用open()方法初始化。
  • 1(初始化):对象已经创建,但未调用send()方法。
  • 2(发送数据):send()方法已经被调用,但是HTTP状态和HTTP头未知。
  • 3(数据传送中):已经开始接收数据。但由于响应数据和HTTP头信息不全,这时尝试获取数据会出错。
  • 4(完成):数据接收完毕。

以下例为例,显示出XMLHttpRequest对象的5种状态过程:

var xhr;
if (window.XMLHttpRequest) {
    //兼容IE7+, Firefox, Chrome, Opear, Safari浏览器
    xhr = new XMLHttpRequest(); //创建一个XMLHttpRequest对象实例
} else {
    //兼容IE5, IE6浏览器
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function () {
    console.log(xhr.readyState);
    if (xhr.readyState == 4 && xhr.status == 200) {
       console.log(xhr.responseText);
    }
}    
xhr.open("GET", "test.php", true);
xhr.send(); //发送请求   

效果:





指定请求状态发生改变时的事件处理程序(事件句柄)readyStatechange事件

当XMLHttpRequest对象的readyState状态发生改变时,会触发 readystatechange事件,通过将事件处理函数赋值给XMLHttpRequest对象的readystatechange属性时,可以为该事件添加事件处理函数。如:

xhr.onreadystatechange = function () {
    console.log(xhr.readyState);
    if (xhr.readyState == 4 && xhr.status == 200) {
       console.log(xhr.responseText);
    }
}    

当状态发生改变时,为readystatechange事件添加事件处理函数来显示5种状态和弹出服务器端的“hello world!”。



获取当前请求的HTTP状态码status

当请求完成后,可以通过XMLHttpRequest对象的status属性来获取当前HTTP请求的状态。

HTTP请求状态码大概有:



以下例为例,查看当前HTTP请求的状态:
var xhr;
if (window.XMLHttpRequest) {
    //兼容IE7+, Firefox, Chrome, Opear, Safari浏览器
    xhr = new XMLHttpRequest(); //创建一个XMLHttpRequest对象实例
} else {
    //兼容IE5, IE6浏览器
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function () {
    console.log(xhr.status); //HTTP请求的状态
    if (xhr.readyState == 4 && xhr.status == 200) {
       console.log(xhr.responseText);
    }
}    
xhr.open("GET", "test.php", true);
xhr.send(); //发送请求   

效果:




获取返回的所有HTTP头信息getAllResponseHeaders()


可以使用XMLHttpRequest对象的getAllResponseHeaders()来获取所有HTTP头信息。getResponseHeader()用于获取一个HTTP头信息。

服务器端代码:
<?php
    header("Author:huang");
    header("web:www.huangchangjiu.com");
    echo "hello world!";
?>

JavaScript代码:
var xhr;
if (window.XMLHttpRequest) {
    //兼容IE7+, Firefox, Chrome, Opear, Safari浏览器
    xhr = new XMLHttpRequest(); //创建一个XMLHttpRequest对象实例
} else {
    //兼容IE5, IE6浏览器
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function () {
    console.log(xhr.getAllResponseHeaders()); //获取所有HTTP头信息
    if (xhr.readyState == 4 && xhr.status == 200) {
       console.log(xhr.responseText);
    }
}    
xhr.open("GET", "test.php", true);
xhr.send(); //发送请求   

效果:





获取返回的数据responseText、responseXML

在XMLHttpRequest对象完成一次Http请求后,可以通过访问 responseText或responseXML来获取返回的数据。
其中:
  • responseText:将返回的数据以字符串的格式返回。
  • responseXML:将返回的数据以XML文档的格式返回。

下面的例子为将返回的数据以XMLX文档的格式返回:

window.onload = function () {
     var xhr;
     if (window.XMLHttpRequest) {
         //兼容IE7+, Firefox, Chrome, Opear, Safari浏览器
         xhr = new XMLHttpRequest(); //创建一个XMLHttpRequest对象实例
     } else {
         //兼容IE5, IE6浏览器
         xhr = new ActiveXObject("Microsoft.XMLHTTP");
     }
     xhr.onreadystatechange = function () {
         if (xhr.readyState == 4 && xhr.status == 200) {
            console.log(xhr.responseXML);
         }
     }    
     xhr.open("GET", "message.xml", true);
     xhr.send(); //发送请求
 }   
 function parseXMLData (date) {
     var childs = data.childNodes;
     if (childs.length > 0) {
         document.body.innerHTML += "<div>" + data.nodeName + "</div>";
         for (var i = 0; i < childs.length; i ++) {
             parseXMLData(childs[i]);
         }
     } else {
         document.body.innerHTML = "<div>" + data.nodeName + data.nodeValue + "</div>";
     }
 }                  

xml文档:
<?xml version="1.0" encoding="uft-8"?>
<list>
  <item>
    <name>Huang</name>
    <date>2017-060-15</date>
    <message>hello world!</message>
  </item>
</list>



取消当前请求abort()

如果需要取消一个正在进行中的请求,可以使用XMLHttpRequest对象的abort()方法来取消。

格式: new XMLHttpRequest.abort();

调用了abort()方法后,XMLHttpRequest对象回到未初始化状态(即readyState为0的状态)。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值