我想創建一個使用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
是顯示「沒有消息呢,是先送一個!」在頁面上,因爲它應該,因爲沒有什麼數據庫 –
控制檯中的任何錯誤? –