Javascript XmlHttpObject不更改其readyState
我正在尝试使用JavaScript实现一个聊天客户端。客户端使用以下构造函数构造:Javascript XmlHttpObject不更改其readyState,javascript,ajax,Javascript,Ajax,我正在尝试使用JavaScript实现一个聊天客户端。客户端使用以下构造函数构造: function ChatClient(endpointUrl) { this.xmlHttp = createXmlHttpRequest(); this.endpointUrl = endpointUrl; me = this; setInterval('me.receiveMessages()', FETCH_MESSAGES_INTERVAL); } functio
function ChatClient(endpointUrl) {
this.xmlHttp = createXmlHttpRequest();
this.endpointUrl = endpointUrl;
me = this;
setInterval('me.receiveMessages()', FETCH_MESSAGES_INTERVAL);
}
function createXmlHttpRequest() {
/* Create a new XMLHttpRequest object to talk to the Web server */
var xmlHttp = false;
/* @cc_on @ */
/*
* @if (@_jscript_version >= 5) try { xmlHttp = new
* ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlHttp = new
* ActiveXObject("Microsoft.XMLHTTP"); } catch (e2) { xmlHttp = false; } }
* @end @
*/
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
return xmlHttp;
}
聊天客户机应该能够在获取消息\u间隔
定义的间隔内从服务器请求消息。代码如下:
ChatClient.prototype.receiveMessages = function() {
this.xmlHttp.open('GET', this.endpointUrl, true);
this.xmlHttp.onreadystatechange = this.handleReceiveMessagesResponse();
this.xmlHttp.send(null);
}
ChatClient.prototype.handleReceiveMessagesResponse = function() {
console.log("readyState = " + this.xmlHttp.readyState);
if (this.xmlHttp.readyState == 4) {
var rawResponse = this.xmlHttp.responseText;
document.getElementById('OutputArea').textContent = rawResponse;
}
}
问题在于,调用HandlerReceiveMessagesResponse时,FireBug cosole显示this.xmlHttp.readyState始终为1(正在加载)。FireBug还显示我的GET请求正在接收来自服务器的expect响应(状态200,字符串“Hello”为body)。有人知道这段代码出了什么问题吗?您正在调用HandlerReceiveMessagesResponse方法并将返回值(未定义)分配给onreadystatechange属性。我怀疑你不是有意的,事实上,你应该把()放在那行的末尾。但是,这仍然不起作用,因为
this
上下文将不是您所期望的被调用函数中的上下文
试试这个:-
ChatClient.prototype.receiveMessages = function() {
var self = this;
this.xmlHttp.open('GET', this.endpointUrl, true);
this.xmlHttp.onreadystatechange = handleReceiveMessagesResponse;
this.xmlHttp.send(null);
function handleReceiveMessagesResponse() {
console.log("readyState = " + self.xmlHttp.readyState);
if (self.xmlHttp.readyState == 4) {
var rawResponse = self.xmlHttp.responseText;
document.getElementById('OutputArea').textContent = rawResponse;
}
}
}
这一行:
this.xmlHttp.onreadystatechange = this.handleReceiveMessagesResponse();
应该是:
this.xmlHttp.onreadystatechange = (function( fn ) {
return function() {
fn.handleReceiveMessagesResponse.apply( fn, arguments );
};
})( this );
从我的头顶上。这种疯狂背后的原因是:
仅接受onreadystatechange
值。调用函数将返回其各自的返回值函数
- 因为您想保留对该的引用,所以我们必须通过将其赋给变量或封装在闭包函数中来封装它,后者就是我所做的
- 然后,我们可以使用
/apply
调用
来更改
方法的“this”变量的上下文。我还传递了这些论点,以防万一handleReceiveMessagesResponse