0

我在php中进行简单的聊天,当我发送用户消息ajax时,页面中没有显示,我现在开始研究ajax,所以我不知道代码有什么问题,我做了就像我在 w3schools 看到的那样

现在我只是想检查消息是否会显示在页面中,而不是在服务器上什么都不做,当我可以解决这个问题时,我会制作发送到数据库的类,我尝试通过邮寄发送,但也不工作

// this is the ajax in the chat.html

<script type="text/javascript">
    let send = document.querySelector('#send-mes');
    send.addEventListener('click', load);

    function load() {
        let msg = chat.msg.value;
        let xml = new XMLHttpRequest();

        xml.onreadystatechange = function() {
            if (this.readystate==4&&this.status==200) {
                    let content = document.querySelector('#content');
                content.innerHTML = this.responseText;
                }
            }
        xml.open('get', 'ajx.php?msg='+msg, true);
        xml.send();
    }
</script>
////////////////////////////////////////////////////////////////////////////

// this is the code in the server ajx.php

$ajx = $_REQUEST['msg'];
echo $ajx;

我希望通过 ajax 发送到服务器的消息出现在#content 标签中(我没有把标签放在这里),但是什么也没发生(稍后我会改进服务器,现在我只想修复这个),如果有人想查看所有代码,可以在我的 github 中查看https://github.com/CristoferPortela/chatbox.git

4

1 回答 1

0

我将您的代码编辑为下面的代码及其工作。

<!DOCTYPE html>
<html>
    <head></head>
    <body>
    
    <div>
        <input id="msg">
        <button id="send-mes">Send</button>
    </div>
    
    <div id="content">
    </div>
    
<script>
    let send = document.querySelector('#send-mes');
    send.addEventListener('click', load);

    function load() {
        let msg = document.querySelector('#msg').value;
        let xml = new XMLHttpRequest();

        xml.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                let content = document.querySelector('#content');
                content.innerHTML = this.response;
            }
        }
        xml.open('GET', 'ajx.php?msg='+msg, true);
        xml.send();
    }
</script>
    
    </body>
</html>

于 2019-03-24T00:10:10.260 回答