ajax GET请求responseText为空
ajax GET request responseText empty
我试图使用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==2
和readyState==4
的区别
我强烈推荐使用jQuery进行AJAX,因为它更加简单和直观。这里是更多信息的链接:http://www.w3schools.com/jquery/jquery_ref_ajax.asp
相关文章:
- 如果文本字段为空,则使用JavaScript应用CSS样式
- ReactJS映射:如何仅在url变量不为空时呈现html链接
- 如果localstorage为空,则显示欢迎消息
- 使用 jQuery 检查所有值是否为空或已填充
- 如果值为空,如何设置输入的默认值?jQuery
- 如何检查元素的内容是否为空,如果为空,请在jquery中删除该元素
- 在MVC 4中,对Controller的Ajax调用为空
- Spring Ajax列表返回,但对象为空
- 输入文本框为空时的阻止按钮asp.网络表单
- $_POST变量为空
- 如果数据为空,Ajax加载不会停止
- 边框颜色是't如果输入为空,则更改
- servlet-为什么XMLHttpRequest responseText始终为空
- GM_xmlhttpRequest responseText在Firefox中为空,但在Chrome中是完美的
- ajax GET请求responseText为空
- responseText为空,但显示在控制台上
- 响应XML为空,尽管responsetext是有效的.net webservice
- XMLHttpRequest状态为4,但responseText为空
- xmlhttprequest中的responseText为空
- XMLHttpRequest的状态为200,但responseText为空