2011-11-28 58 views
0

使用AJAX類。下面是代碼:面向對象的JavaScript - AJAX類

function AjaxRequest(params) { 
    if (params) { 
     this.params = params; 
     this.type = "POST"; 
     this.url = "login.ajax.php"; 
     this.contentType = "application/x-www-form-urlencoded"; 
     this.contentLength = params.length; 
    } 
} 

AjaxRequest.prototype.createXmlHttpObject = function() { 
    try { 
     this.xmlHttp = new XMLHttpRequest(); 
    } 
    catch (e) { 
     try { 
      this.xmlHttp = new ActiveXObject("Microsoft.XMLHttp"); 
     } 
     catch (e) {} 
    } 

    if (!this.xmlHttp) { 
     alert("Error creating XMLHttpRequestObject"); 
    } 
} 

AjaxRequest.prototype.process = function() { 
    try { 
     if (this.xmlHttp) { 
      this.xmlHttp.onreadystatechange = this.handleRequestStateChange(); 
      this.xmlHttp.open(this.type, this.url, true); 
      this.xmlHttp.setRequestHeader("Content-Type", this.contentType); 
      this.xmlHttp.setRequestHeader("Content-Length", this.contentLength); 
      this.xmlHttp.send(this.params); 
      } 
     } 
     catch (e) { 
      document.getElementById("loading").innerHTML = ""; 
      alert("Unable to connect to server"); 
     } 
    } 

AjaxRequest.prototype.handleRequestStateChange = function() { 
    try { 
     if (this.xmlHttp.readyState == 4 && this.xmlHttp.status == 200) { 
      this.handleServerResponse(); 
     } 
    } 
    catch (e) { 
     alert(this.xmlHttp.statusText); 
    } 
} 

AjaxRequest.prototype.handleServerResponse = function() { 
    try { 
     document.getElementById("loading").innerHTML = this.xmlHttp.responseText; 
    } 
    catch (e) { 
     alert("Error reading server response"); 
    } 
} 

然後明顯實例,像這樣:

var ajaxRequest = new AjaxRequest(params); 
ajaxRequest.createXmlHttpObject(); 
ajaxRequest.process(); 

我在與handleRequestStateChange方法的問題,因爲它處理xmlHttp.onreadystatechange。一般來說,當你爲onreadystatechange定義一個函數時,你不需要在被調用的時候加入括號,例如xmlHttp.onreadystatechange = handleRequestStateChange;但是因爲我試圖將handleRequestStateChange()保留在類的範圍內,所以我遇到了onreadystatechange的問題。該函數確實被調用,但它似乎卡住了0的readyState。

任何幫助或洞察力將不勝感激。請讓我知道是否需要包含更多細節,或者如果我對某些事情不清楚。

+0

你有沒有嘗試用匿名函數包裝它? 'this.xmlHttp.onreadystatechange = function(){this.handleRequestStateChange();};' –

+0

以防萬一你不知道,這已經在http://api.jquery.com/jQuery.post/ – NimChimpsky

+0

@ AnthonyGrist我曾嘗試過,但這不適合我。下面的解決方案確實有效。謝謝你的幫助。 – Brett

回答

3
AjaxRequest.prototype.handleRequestStateChange = function() { 
    var self = this; 

    return function() { 
     try { 
      if (self.xmlHttp.readyState == 4 && self.xmlHttp.status == 200) { 
       self.handleServerResponse(); 
      } 
     } 
     catch (e) { 
      alert(self.xmlHttp.statusText); 
     } 
    }; 
} 

現在,當你做this.xmlHttp.onreadystatechange = this.handleRequestStateChange();,它將返回已被困在正確this參考self,這是實際onreadystatechange函數內部使用的約束功能。

+0

此解決方案爲我工作,謝謝! – Brett