我正在创建一个聊天,但每次我发送一条消息,它都不会让我发送另一条消息,就像表单不起作用?

时间:2015-04-05 05:23:09

标签: javascript jquery ajax chat

当我在聊天中发布消息时,它不会让我再次发帖。我相信这是与发送相关的代码:

window.typing = false;
var posted = 0;
var canPost = 1;
var donotrefresh = 0;

document.forms['send'].addEventListener('submit', function (event) {

    event.preventDefault();
    if (!this.message.value || !canPost) {
        return 0;
    }
    var form = this;
    var message = this.message.value;
    this.message.value = "";
    this.message.focus();
    var ajax = new XMLHttpRequest();

    posted = 1;
    canPost = 0;
    chat.refresh();
    chat.messages.scrollTop = 0;

    ajax.onreadystatechange = function () {
        if (ajax.readyState >= 4 && ajax.status == 200) {
            if (!ajax.responseText) {
               canPost = 1;
               posted = 0;
            }
        }
    }

    ajax.open("GET", "/chat/ajax.php?req=post&chatmsg=" + encodeURIComponent(message), true);
    ajax.send(null);
}, false);

这是我的提交代码:

<form name="send" style="height:100px;width:100%">
    <input type="text" name="message" style="width:60%;height:2em;resize:vertical;opacity:0.8;" maxlength="220" placeholder="Your message to send..." required />
    <input type="submit" value="Send" style="vertical-align:top;opacity:0.8;" />
</form>

1 个答案:

答案 0 :(得分:0)

尝试删除if(!ajax.responseText)

ajax.onreadystatechange = function () {
    if (ajax.readyState >= 4 && ajax.status == 200) {
        canPost = 1;
        posted = 0;
    }
}

你需要&#34;发布&#34;变量?看起来这个代码已经不再使用了。在我看来,canPost的目的是同时避免请求。在这里避免这种情况真的有意义吗?