Ajax技術的工做原理

 

Ajax技術核心是 XMLHttpRequest,工做原理能夠分爲4步html

一、建立Ajax對象瀏覽器

var xhr = new XMLHttpRequest(); 

二、鏈接服務器服務器

xhr.open('get','test.html',true);

三、發送請求spa

xhr.send();

四、獲取響應code


xhr.onreadystatechange = function(){
  if(xhr.readystate == 4){ //請求的狀態碼
                 /*
                   0:請求尚未創建(open執行前)
                   1:請求創建了還沒發送(執行了open)
                   2:請求正式發送(執行了send)
                   3:請求已受理,有部分數據能夠用,但尚未處理完成
                   4:請求徹底處理完成
                 */

    alert(xhr.responseText); //返回的數據

  }
}

 下面是完整代碼htm

function loadXMLDoc(){  var xhr;  if(window.XMLHttpRequest){    xhr = new XMLHttpRequest(); //非IE瀏覽器建立 XMLHttpRequest 對象   }else {    xhr = new ActiveObject("Microsoft.XMLHTTP"); //IE瀏覽器建立 XMLHttpQuest 對象  }    xhr.open('get','test.html',true);  xhr.send();    xhr.onreadystatechange = function(){      if(xhr.readyState == 4 && xhr.status == 200){      document.getElementById("myDiv").innerHTML = xhr.reponseText;    }  }}
相關文章
相關標籤/搜索