2015-10-19 161 views
1

我想创建一个使用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变量中。

+0

之间的区别难道当你在浏览器中打开loadmessages.php直接与你得到什么 – Svetoslav

+0

是显示“没有消息呢,是先送一个!”在页面上,因为它应该,因为没有什么数据库 –

+0

控制台中的任何错误? –

回答

2

,则应该更换if子句readyState象下面这样:

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

因为这个回调每次触发readyState变化和您正在测试的值2这是sent在这一点上,在xhttp.responseText

没有可用的响应看到这里What do the different readystates in XMLHttpRequest mean, and how can I use them?

在这里稍微详细Why XmlHttpRequest readyState = 2 on 200 HTTP response code
readyState==2readyState==4

+0

谢谢!我现在感觉非常愚蠢。 –

+0

不客气! –

0

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

+0

我试图从这个项目中离开jQuery。我知道jQuery的强大功能以及它的容易程度,但是我创建这个项目的关键是不要只使用jQuery一次。不管怎么说,还是要谢谢你! –

+0

好吧,我只是建议,如果你不知道jquery。 – fico7489

+0

@ fico7489我想每个人都听说过jQuery :) –