dongya6997 2012-08-08 00:44 采纳率: 0%
浏览 21
已采纳

检查是否有带ajax的新消息

I have put up some code to make an ajax, php, mysql chat in real time... this is my code:

-jQuery/Ajax

$(function(){
    setInterval(function() {
    $('#chMsgCont').load('./ajax/msg.php');
       var div = $('#chMsgCont');
         var o = div.offset().top;  

   div.scrollTop( o + 12302012 );
    }
    ,1000);
});

"./ajax/msg.php"

<?php
include("../system/config.site.php");
$query = mysql_query("SELECT * FROM chat_msg ORDER BY timestamp ASC");
while($p = mysql_fetch_assoc($query)) {
    $auth = mysql_fetch_assoc(mysql_query("SELECT * FROM chat_users WHERE id = '".$p['auth_id']."'"));
?>
<div class="chatMsg">
<p id="chatPMsg">
<span class="chatTime"><?php echo date("H:i", $p['timestamp']); ?></span>
<b><?php echo $auth['name']." ".$auth['surname']; ?></b><br />
<?php echo stripslashes($p['msg']); ?>
</p>
<p id="chatImg">
<img src="./images/thumb<?php echo $p['auth_id']; ?>.png" />
</p>
<div style="clear:both;"><!– –> </div>
</div>
<?php
}
?>

I haven't found any method for not loading every second the "msg.php" file... I thought: is it possible to load initially the messages and then with setIntervall check for new messages to append to #chMsgCont? I think it is possible, but i can't figure out how to code it :/, can anyone help me?

  • 写回答

1条回答 默认 最新

  • douluan5444 2012-08-08 00:53
    关注

    Yes it is possible to load all messages upon initial page load; then subsequently update the chat window with new messages (have you ever wondered how Gmail auto populates new mail into your Inbox without a page refresh? Lots of AJAX requests).

    You're on the right track. Just make sure you have a column in your MySQL database that holds a "yes/no" value on whether its a new message or not. Then everytime a new message is fetched using ajax/msg.php, in addition to fetching and outputting the content, perform a SQL update to update the fetched data as well.

    Once you have that working you can further optimize your chat application by creating a simplier MySQL SELECT statement that simply checks the count of "new" rows (SELECT COUNT(new_message) FROM messages). Then check the value returned and whether it's greater than 0 before attempting to append content. I would also check for empty return data in your JavaScript to prevent from unnecessarily manipulating DOM elements.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊