DIV CSS 佈局教程網

以物件導向封裝XMLHttpRequest非同步請求
編輯:AJAX基礎知識     

本文示範如何以物件導向的方式,將XMLHttpRequest的各個生命週期階段封裝成一個CallBackObject類,讓非同步請求具備清晰的狀態回呼與可擴充性。

核心類別設計

這個類別透過prototype動態擴充方法,涵蓋物件的建立、回呼註冊、請求送出、中止,以及各階段的狀態處理。以下是完整程式碼:

function CallBackObject()
{
  this.XmlHttp = this.GetHttpObject();
}
CallBackObject.prototype.GetHttpObject = function() //動態為CallBackObject的原型添加GetHttpObject共有方法
{
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
  try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp = false; } }
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try { xmlhttp = new XMLHttpRequest(); } catch (e) { xmlhttp = false; }
  }
  return xmlhttp;
}
CallBackObject.prototype.DoCallBack = function(URL)
{
  if( this.XmlHttp )
  {
    if( this.XmlHttp.readyState == 4 || this.XmlHttp.readyState == 0 )
    {
      var oThis = this;
      this.XmlHttp.onreadystatechange = function() {
        oThis.ReadyStateChange();
      };
      this.XmlHttp.open('POST', URL);
      this.XmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      this.XmlHttp.send(null);
    }
  }
}
CallBackObject.prototype.AbortCallBack = function()
{
  if( this.XmlHttp ) this.XmlHttp.abort();
}
CallBackObject.prototype.ReadyStateChange = function() {
  if (this.XmlHttp.readyState == 1) { this.OnLoading(); }
  else if (this.XmlHttp.readyState == 2) { this.OnLoaded(); }
  else if (this.XmlHttp.readyState == 3) { this.OnInteractive(); }
  else if (this.XmlHttp.readyState == 4) {
    if (this.XmlHttp.status == 0) this.OnAbort();
    else if (this.XmlHttp.status == 200 && this.XmlHttp.statusText == "OK")
      this.OnComplete(this.XmlHttp.responseText, this.XmlHttp.responseXML);
    else this.OnError(this.XmlHttp.status, this.XmlHttp.statusText, this.XmlHttp.responseText);
  }
}
CallBackObject.prototype.OnLoading = function() { }
CallBackObject.prototype.OnLoaded = function() { }
CallBackObject.prototype.OnInteractive = function() { }
CallBackObject.prototype.OnComplete = function(responseText, responseXml) { }
CallBackObject.prototype.OnAbort = function() { }
CallBackObject.prototype.OnError = function(status, statusText) { }

呼叫方式

使用時只需建立物件、覆寫所需的狀態回呼方法,再呼叫DoCallBack即可:

function createRequest()
{
  var name = escape(document.getElementById("name").value);
  var cbo = new CallBackObject();
  cbo.OnComplete = Cbo_Complete;
  cbo.onError = Cbo_Error;
  cbo.OnLoaded = OnLoading;
  cbo.DoCallBack("AjaxTest.aspx?name=" + name);
}

相關屬性補充

responseText:readyState為0、1、2時為空字串;為3時包含尚未完成的回應;為4時包含完整回應。
responseXML:僅在readyState為4且Content-Type為text/xml等XML類型時才有值,否則為null。
status:描述HTTP狀態碼,僅在readyState為3或4時可用。
statusText:描述HTTP狀態碼的文字,同樣僅在readyState為3或4時可用。

透過這種物件導向的封裝,每個生命週期階段都對應到明確的回呼方法,讓非同步請求的邏輯更清晰、更易於擴充與維護。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved