天天看點

xmlhttp應用

1,Xmlhttp是一種浏覽器對象, 可用于模拟http的GET和POST請求。配合JavaScript可以實作頁面資料在無重新整理下的定時​​資料更新​​,如果應用在聊天室、文字直播上可以取得較好的視覺效果。

2,在IE中XmlHttp被實作為ActiveX對象,通常使用var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");也可以使用var xmlhttp = createobject("MiCROSOFT.XMLHTTP") 來建立一個對象,然後使用該對象的open方法來發出一個Http請求。

var strURL = admin;

function xmlhttpPost(cell,strURL,action) {
      var xmlHttpReq = false;
      var self = this;
      if (window.XMLHttpRequest) {
          self.xmlHttpReq = new XMLHttpRequest();
      }
      else if (window.ActiveXObject) {
          self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
      }
      self.xmlHttpReq.open('POST', strURL, true);//會進入對應的servlet
      self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      self.xmlHttpReq.onreadystatechange = function() {
          if (self.xmlHttpReq.readyState == 4 ) {
            if(self.xmlHttpReq.status==200){ 
               // updatepage(self.xmlHttpReq.responseText,responsediv);
               var responseMsg = self.xmlHttpReq.responseText;
               responseEvent(cell,responseMsg);
            }else{
          alert('Ajax Request Error.');
        }
          }
      
      }
      self.xmlHttpReq.send(action);
  }      
application/x-www-form-urlencoded:鍵值對形式送出      

 當action為get時候,浏覽器用x-www-form-urlencoded的編碼方式把form資料轉換成一個字串(name1=value1&name2=value2...),然後把這個字串append到url後面,用?分割,加載這個新的url。 當action為post時候,浏覽器把form資料封裝到http body中,然後發送到server。 

// 請求的狀态有5個值:0=未初始化;1=正在加載;2=已經加載;3=互動中;4=完成;
    if (xmlHttpReq.readyState == 4) {
        // 200對應OK,如404=未找到網頁
        if (xmlHttpReq.status == 200) {
            // alert(xmlHttpReq.responseText);
        }
    }