2015-08-17 48 views
1

我最近開始爲某些人開發網站,而且我似乎無法使其正常工作。我的問題是我不知道如何刷新我的留言箱div。如果你能幫助我,我會非常開心。刷新一個留言框

<div id="chatbox"> 
     <div class="chatboxi"> 
    <?php 
     $connection = mysql_connect('LocalDB', 'DB', 'Pass'); 
     mysql_select_db('DBO'); 

     $query = "SELECT * FROM (SELECT * FROM shoutbox ORDER BY id DESC LIMIT 15) sub ORDER BY id Desc"; // Sorts them and takes the 10 first by ID. 

     $result = mysql_query($query); 

     echo "<table>"; // start a table tag in the HTML 

     while($row = mysql_fetch_array($result)){ //Creates a loop to loop through results 
     echo "<tr><td>" . $row['name'] . "</td><td>:" . $row['post'] . "</td></tr>"; //$row['index'] the index here is a field name 


     } 

     ?> 

     </div> 
    </div> 

</form> 

<form method="POST" name="chatbarf"> 
    <textarea cols="2" rows="3" id="chatbar" name="chatbar"> 
    </textarea> 
    <input type="submit" value="Send" id="Send" name="Send" onsubmit=""> 
</form> 

我一直在嘗試使用此代碼:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script> 
<script> 
var auto_refresh = setInterval(
function() 
{ 
$('#chatbox').fadeOut('slow').load('chat.php').fadeIn("slow"); 
}, 20000); 
</script> 

它沒有很好地工作。它刷新了整個頁面,並使所有內容翻了一番。

+2

搜索有關javascript ajax輪詢,如果它是一個定期更新,或websocket,如果它的實時。 – VMcreator

+0

我同意VMcreator。你會在網上找到許多Ajax示例並且是最簡單的選擇,websocket稍微複雜一些。 Ajax將在幕後獲取/發佈,無需重定向或重新加載頁面,websockets用於打開連接並監聽更改。 – NewToJS

+0

我似乎無法讓他們正常工作。這就是爲什麼我在這裏問。 – Jacob

回答

0

這是您的起點。

SQL來SQLI & jQuery的DOM已準備就緒:

我已經更新了PHP從SQL到SQLI我建議,但我還是建議你研究SQLI因爲它瞭解源代碼是非常重要的,你在你的服務器上運行。

我也創建了一個叫做GetShouts的函數。原因是如果你決定改變你的發帖方法(添加新的發言)到一個AJAX方法,你可以調用GetShouts(),它會在用戶添加一個新留言時更新留言箱,這將向用戶確認留言已被添加。

HTML文件:

<!DOCTYPE html> 
<html><head> 
<title>Shoutbox</title> 
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js'></script> 
<script type="text/javascript"> 
$(function() { //DOM is ready 
function GetShouts(){ 
$('#chatbox').fadeOut('slow').load('chat.php').fadeIn("slow"); 
} 
//Set interval 
var auto_refresh = setInterval(GetShouts, 20000); 
//Get shouts 
GetShouts(); 
}); 
</script> 
</head> 
<body> 
<div id="chatbox"></div> 
</body></html> 

PHP文件(chat.php):

<?php 
$mysqli = new mysqli("LocalDB", "DB", "Pass", "DBO"); 
if ($mysqli->connect_errno) { 
die("Connection Failed"); 
exit(); 
} 
$Output="<table>"; 
if ($result = $mysqli->query("SELECT * FROM shoutbox LIMIT 15")) { 
    while ($row = $result->fetch_assoc()) { 
     $Output.='<tr><td>'.$row["name"].'</td><td>'.$row["post"].'</td></tr>'; 
    } 
$result->free(); 
} 
$mysqli->close(); 
$Output.="</table>"; 
echo $Output; 
?> 

如果你不明白上述任何的源代碼,請發表評論下面,我會盡快回復你,並在源代碼中添加必要的註釋。

鑑賞通過標記答案顯示。

我希望這會有所幫助。快樂的編碼!

+0

非常感謝!它像一個魅力一樣工作! – Jacob

+0

@Jacob樂意幫忙!如果您有任何問題,請發表評論。 – NewToJS