繁体   English   中英

ajax GET请求responseText为空

[英]ajax GET request responseText empty

我正在尝试使用AJAX创建聊天框,但是由于某种原因,我的xhttp.responseText为空。 在萤火虫中,我可以看到正在发送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变量中。

您应该更改readyStateif子句,如下所示:

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

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

请参阅此处XMLHttpRequest中不同的readystate是什么意思,我该如何使用它们?

在这里稍微详细一点, 为什么XmlHttpRequest readyState = 2 on 200 HTTP response code
readyState==2readyState==4之间的区别

我强烈建议将jQuery用于AJAX,因为它更加简单直观。 这是更多信息的链接: http : //www.w3schools.com/jquery/jquery_ref_ajax.asp

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM