ajax GET请求responseText为空

ajax GET request responseText empty

本文关键字:为空 responseText 请求 GET ajax      更新时间:2023-09-26

我试图使用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变量中。

您应该将if子句更改为readyState,如下所示:

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

由于每次readyState变化时都会触发此回调,并且您正在测试2的值,即sent,此时xhttp.responseText中没有响应

查看这里XMLHttpRequest中不同的就绪状态是什么意思,我如何使用它们?

在这里稍微详细一点为什么XmlHttpRequest readyState = 2在200 HTTP响应代码
readyState==2readyState==4的区别

我强烈推荐使用jQuery进行AJAX,因为它更加简单和直观。这里是更多信息的链接:http://www.w3schools.com/jquery/jquery_ref_ajax.asp