DIV CSS 佈局教程網

打造你的專屬Ajax類:優雅封裝非同步請求
編輯:AJAX基礎知識     

每次撰寫Ajax都要重複處理XMLHttpRequest物件的建立與狀態判斷,既繁瑣又容易出錯。本文提供一個輕巧的Ajax類,讓你能優雅地監聽不同的HTTP狀態碼、自訂GET或POST請求,並以鏈式呼叫簡化程式碼。

基本用法

var ajax = new AjaxObj(url);
ajax.addListener(200, function(r){
  alert(r);
});
ajax.send();

鏈式呼叫

由於每個方法都會回傳物件本身,因此也能連續呼叫:

var ajax = new AjaxObj(url).addListener(200, function(r){
  alert(r);
}).send();

此外,這個類還支援自訂的POST或GET請求方式,並可監聽不同的HTTP狀態碼,非常靈活。

完整程式碼

AjaxObj = function(url, method, content){
    this.r = null;
    this.url = url;
    this.method = method;
    this.content = content;
    this.header = {};
    this.header["Connection"] = "close";
    this.header["Content-type"] = "application/x-www-form-urlencoded";
    var self = this;
    if(window.XMLHttpRequest){
      this.r = new XMLHttpRequest();
    }else if(window.ActiveXObject){
      try {
        this.r = new ActiveXObject("Msxml2.XMLHTTP");
      } catch(e) {
        try{
          this.r = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(e) {
        }
      }
    }
    this.addListener = function(http_status, func){
      if(!this.L)
        this.L=[];
      this.L[http_status] = func;
      return this;
    };
    this.setHeader = function(name, value){
      this.header[name] = value;
      this.r.setRequestHeader(name, value);
      return this;
    };
    this.send = function(){
      if(this.method != "post" && this.method != "get")
        this.method = "get";
      this.r.open(this.method, this.url, true);
      for(var h in this.header) {
        this.r.setRequestHeader(h, this.header[h]);
      }
      this.r.send(this.content);
    };
    if(this.r) this.r.onreadystatechange = function(){
      if(self.r.readyState == 4 && self.L[self.r.status] != null)
        self.L[self.r.status](self.r.responseText);
    };
};

設計亮點

這個類在建構時便完成XMLHttpRequest物件的建立與跨瀏覽器相容處理,並預設好常用標頭。addListener方法允許你針對特定狀態碼註冊回呼函式,send方法則統一處理連線開啟、標頭設定與請求送出。透過this回傳,實現了流暢的鏈式呼叫,讓Ajax程式碼既簡潔又易讀。

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