gpt4 book ai didi

javascript - XmlHttpObject 不改变它的 readyState

转载 作者:行者123 更新时间:2023-11-30 06:09:03 24 4
gpt4 key购买 nike

我正在尝试使用 JavaScript 实现聊天客户端。使用以下构造函数构造客户端:

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;
}

聊天客户端应该能够在 FETCH_MESSAGES_INTERVAL 定义的时间间隔内从服务器请求消息。这是代码:

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;
}
}

问题是当调用 handleReceiveMessagesReponse 时,FireBug 控制台显示 this.xmlHttp.readyState 始终为 1(正在加载)。 FireBug 还显示我的 GET 请求正在接收来自服务器的预期响应(状态 200,正文为字符串“Hello”)。有谁知道这段代码有什么问题吗?

最佳答案

您调用 handleReceiveMessagesResponse 方法并将返回值(未定义)分配给 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;
}
}
}

关于javascript - XmlHttpObject 不改变它的 readyState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1405484/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com