我想创建一个使用AJAX聊天箱,但由于某种原因,我的xhttp.responseText为空。在firebug中,我可以看到正在发送一个GET请求,它甚至用正确的文本进行响应,但由于某些原因,此文本不会放入responseText中。ajax 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!');
?>
因为没有什么是数据库然而,它只是回应“没有消息,是第一个发送!”。我可以看到这个响应,如果我打开萤火虫,但是这个文本不在responseText变量中。
之间的区别难道当你在浏览器中打开loadmessages.php直接与你得到什么 – Svetoslav
是显示“没有消息呢,是先送一个!”在页面上,因为它应该,因为没有什么数据库 –
控制台中的任何错误? –