2011-11-28 59 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