AJAX - 創(chuàng)建 XMLHttpRequest 對象
XMLHttpRequest 對象
XMLHttpRequest對象是Ajax技術(shù)的核心。
所有現(xiàn)代瀏覽器均支持 XMLHttpRequest 對象(IE5 和 IE6 使用 ActiveXObject)。
不刷新頁面就和服務(wù)器進行交互是Ajax最大的特點。這個重要的特點主要歸功于XMLHttpRequest對象。使用XMLHttpRequest對象使得網(wǎng)頁應(yīng)用程序像windows應(yīng)用程序一樣,能夠及時響應(yīng)用戶與服務(wù)器之間的交互,不必進行頁面刷新或者跳轉(zhuǎn),并且能夠進行一系列的數(shù)據(jù)處理,這些功能可以使用戶的等待時間縮短,同時也減輕了服務(wù)器端的負(fù)載。
創(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 ::
<!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</h2></div> <button type="button" onclick="loadXMLDoc()">點擊修改</button> </body> </html>