2015-08-17 47 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