我正在尝试使用AJAX创建聊天框,但是由于某种原因,我的xhttp.responseText为空。在firebug中,我可以看到正在发送GET请求,它甚至使用正确的文本进行响应,但是由于某种原因,该文本只是没有被放入responseText中。

这是我的index.html:

<!doctype html>

<html>

<head>
    <meta charset="utf-8"/>
    <title>Chatroom</title>
    <script>

    function setup() {
        ajaxRequest( 'GET', 'loadmessages.php', updateChat);
        setInterval(function () {
            ajaxRequest( 'GET', 'loadmessages.php', updateChat);
        }, 1000);
    }

    function updateChat(xhttp) {
        document.getElementById( 'chat' ).innerHTML = xhttp.responseText;
    }

    function ajaxRequest( method, file, cfunc ) {
        xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function () {
            if(xhttp.readyState == 2 && xhttp.status == 200) {
                cfunc(xhttp);
            }
        }
        xhttp.open( method, file, true);
        xhttp.send();
    }

    </script>
</head>

<body onload="setup();">
    <div id="chat">

    </div>
</body>

</html>


这是loadmessages.php:

<?php

include( 'connect.php' );


$query = "SELECT * FROM messages ORDER BY id DESC";
$result = mysqli_query($conn, $query);

if( mysqli_num_rows($result) > 0 ) {
    $output = "";
    while( $row = mysqli_fetch_assoc($result) ) {
        $id = $row['id'];
        $name = $row['name'];
        $content = $row['content'];
        $time = $row['time'];

        $output .= "[sent by $name on $time] $content <hr/>";
    }
    echo $output;
} else {
    echo "No messages yet, be the first to send one!";
}

mysqli_close($conn);
?>


和connect.php:

<?php

$conn = mysqli_connect( 'localhost', 'root', '', 'chatroom' ) or die( 'Couldn\'t connect to database!' );

?>


由于数据库中还没有任何内容,它只会显示“尚无消息,请第一个发送消息!”。如果打开Firebug,我可以看到此响应,但是此文本不在responseText变量中。

最佳答案

您应该像下面这样更改ifreadyState子句:

xhttp.onreadystatechange = function () {
    if(xhttp.readyState == 4) {
        cfunc(xhttp);
    }
}


由于每次readyState更改时都会触发该回调,并且您正在测试值为2sent,因此xhttp.responseText中没有可用的响应

见这里What do the different readystates in XMLHttpRequest mean, and how can I use them?

在这里更详细地Why XmlHttpRequest readyState = 2 on 200 HTTP response code
readyState==2readyState==4之间的区别

关于javascript - ajax GET请求responseText为空,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33216641/

10-10 16:28