每次将<div>新消息插入数据库(MySQL)时刷新聊天



我一直在网上搜索一个代码,每当收到来自其他聊天用户的新消息时,该代码就会刷新聊天<div>。我读过关于setTimeout()setInterval()的文章,但需要更有经验的开发人员的建议和帮助。

最好的例子就是这个网站。除非刷新浏览器,否则您不会立即看到通知。我想最好的例子是facebook。无论何时更新数据库,都会立即弹出通知,而不会刷新浏览器。

这是我的密码。

$check_sql = ("SELECT time from messages where conversation_id = '".$con_id."' ");
$check_query = mysqli_query($con, $check_sql) or die ("ERROR checking:".mysqli_error($con);
while($row = mysqli_fetch_assoc($check_query){
$current_time = date_default_timezone_get();
$message_time_sent = $row['time'];
$cal = $message_time_sent->diff($current_time);
$ans = $cal->format("%D %H:%i:%s");
sscanf($ans,"%d %d:%d:%d ", $day, $hr, $min, $sec);
if (($day == 0) && ($hr == 0) && ($min == 0) && ($sec >0)){
//do something here to get receive message automatically and notification....
}

我想要实现的目标:

  1. Facebook在不刷新浏览器的情况下自动接收消息。我希望能是这样
  2. 在不刷新浏览器的情况下自动弹出通知,我认为这并不重要,一旦我们找到了第1项,剩下的就都好了

使用setInteval()的棘手之处在于,浏览器会不断刷新<div>聊天,因此当用户输入要发送的文本时,每次刷新都会消失。请原谅我的英语。。。。

那么,有没有合适的方法来处理这个问题。。。。

setInterval-set-interval将在您设置的每个间隔调用您的函数

setInterval示例:https://repl.it/OE1o

<html>
<body>
<div id="sample">
Day Mon DD YYYY HH:MM:SS GMT+XXX (Time Zone)
</div>
</body>
</html>
<script>
var sample = document.getElementById('sample');
setInterval(
// Here is where to do things like dom manipulation
function() {
sample.innerHTML = new Date;
},
// Here is where you set the interval asuming I want to update every 1 second
1000
);
</script>

setTimeout-一旦达到超时,就会调用。

setTimeout示例:https://repl.it/OE3H

setTimeout(
// This function will be called once the timeout is reached
function() {
console.log('Hello World');
},
// The timeout is 5 seconds
5000
);

最新更新