XMLHttpRequest 是 AJAX 的基礎(chǔ)。


XMLHttpRequest 對象

所有現(xiàn)代瀏覽器均支持 XMLHttpRequest 對象(IE5 和 IE6 使用 ActiveXObject)。

XMLHttpRequest 用于在后臺與服務(wù)器交換數(shù)據(jù)。這意味著可以在不重新加載整個網(wǎng)頁的情況下,對網(wǎng)頁的某部分進(jìn)行更新。


創(chuàng)建 XMLHttpRequest 對象

所有現(xiàn)代瀏覽器(IE7+、Firefox、Chrome、Safari 以及 Opera)均內(nèi)建 XMLHttpRequest 對象。

創(chuàng)建 XMLHttpRequest 對象的語法:

variable=new XMLHttpRequest();

老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 對象:

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

為了應(yīng)對所有的現(xiàn)代瀏覽器,包括 IE5 和 IE6,請檢查瀏覽器是否支持 XMLHttpRequest 對象。如果支持,則創(chuàng)建 XMLHttpRequest 對象。如果不支持,則創(chuàng)建 ActiveXObject ::

實(shí)例

<html><!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","/try/ajax/ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>

<div id="myDiv"><h2>使用 AJAX 修改該文本內(nèi)容</h2></div>
<button type="button" onclick="loadXMLDoc()">修改內(nèi)容</button>

</body>
</html>

運(yùn)行實(shí)例 ?

點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例

在下一章中,您將學(xué)習(xí)發(fā)送服務(wù)器請求的知識。