2015-10-19 159 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 :) –