在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。该函数确实会被调用,但似乎卡在readyState为0的情况下。任何帮助或见识将不胜感激。请让我知道是否需要包含更多详细信息,或者不清楚。
最佳答案
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
中,该引用在实际的函数内部使用。