實現AJAX的基本步驟

要完整實現一個AJAX異步調用和局部刷新,一般須要如下幾個步驟:javascript

(1)建立XMLHttpRequest對象,也就是建立一個異步調用對象.

 //IE6以上
var xhr= new XMLHttpRequest();

//IE6
var xhr=new ActiveXObject("Microsoft.XMLHTTP")


  (2)建立一個新的HTTP請求,並指定該HTTP請求的方法、URL及驗證信息.

   xhr.open(方法,url,是否異步)

  (3)設置響應HTTP請求狀態變化的函數.

<script type="text/javascript"> function getDoc(){
    var xmlhttp;
    if(window.xmlhttpRequest){
        xmlhttp=new XMLHttpRequest();
    }
    else{
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");//for IE6
    }
    xmlhttp.onreadystatechange = function(){
        if(xmlhttp.readyState==4&&xmlhttp.status==200){
            document.getElementById("myId").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", index.php,true);
    xmlhttp.send(); } </script> </head> <body>
    <button type="button" onclick="getDoc()">請求數據</button> </body>

  (4)發送HTTP請求.
      xmlhttp.send();

  (5)獲取異步調用返回的數據.

  (6)使用JavaScript和DOM實現局部刷新.
相關文章
相關標籤/搜索