Ajax技術能向服務器異步請求額外的數據,會帶來更好的用戶體驗。
Ajax技術核心:XMLHttpRequest對象(簡稱XHR)。
XHR爲向服務器發送請求和解析服務器響應提供了流暢的接口。
一、建立XMLHttpRequest對象
建立XMLHttpRequest對象:
1 var xhr = new XMLHttpRequest();
注:IE7+、Firefox、Opera、Chrome和Safari支持原生XHR對象。
(可是我測試IE5也支持原生XHR對象,多是作了更新)
IE7及以前的版本須要使用MSXML庫中的XHR對象。
以下所示,能夠兼容幾乎全部瀏覽器:
1 function createXHR() { 2 if(typeof XMLHttpRequest != "undefined"){ 3 return new XMLHttpRequest(); //IE7+、Firefox、Opera、Chrome、Safari 4 } 5 else if(typeof ActiveXObject != "undefined"){ 6 return new ActiveXObject("Microsoft.XMLHTTP"); //IE7及之前版本的瀏覽器 7 } 8 else{ 9 throw new Error("No XHR object available."); 10 } 11 } 12 var xhr = createXHR();
二、XHR用法php
1 var xhr = createXHR(); //建立XHR對象 2 xhr.onreadystatechange = function(){ //readyState狀態改變及觸發onreadystatechange事件 3 if(xhr.readyState == 4){ //readyState狀態改變可從0到4,4表示全部數據已就緒 4 if((xhr.status >= 200 && xhr.status <300) || xhr.status == 304){ //status爲200,響應成功;爲304,表示請求的資源未被修改 5 alert(xhr.responseText); //responseText表示響應主體返回的文本 6 } else { 7 alert(「Request was unsuccessful: 」 + xhr.status); 8 } 9 } 10 }; 11 xhr.open(「get」, 「test.php」, true); //啓動一個請求以備發送 12 xhr.send(null); //發送請求