【发布时间】:2011-11-28 16:51:05
【问题描述】:
处理 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 上。
任何帮助或见解将不胜感激。如果需要包含更多详细信息,或者我不清楚某些内容,请告诉我。
【问题讨论】:
-
您是否尝试过将其包装在匿名函数中?
this.xmlHttp.onreadystatechange = function() {this.handleRequestStateChange();}; -
以防万一你不知道,这在api.jquery.com/jQuery.post之前已经完成了
-
@AnthonyGrist 我试过了,但它对我不起作用。然而,下面的解决方案确实有效。感谢您的帮助。
标签: javascript ajax oop scope onreadystatechange