我需要有关实时更新消息的建议,这是我的代码:
<script>
function fetch_messages(){
var user_id = "1" // example id
$.ajax({
url: "do_fetch.php",
type: "POST",
data: { user_id : user_id },
dataType: "json",
success: function(data) {
for (var i = 0; i < data.length; i++) {
$("#messages_list").append('<div id="'+data.id+'">'+data.message+'</div>');
}
setTimeout("fetch_messages()", 3000);
}
});
}
$(function(){
fetch_messages();
});
</script>
并且有 div 消息:
<div id="messages">
</div>
php代码:
<?php
include('connection.php')
$user_id = $_POST['user_id'];
$my_id = $_SESSION['user_id'];
$sql = 'SELECT * FROM messages WHERE user_id = '.mysql_real_escape_string($user_id).' AND my_id = '.mysql_real_escape_string($my_id);
$result = mysql_query($sql, $connection);
echo json_encode($result);
?>
此代码有效,但我不想阅读所有消息并显示它们,我只需要加载新消息,那么我应该怎么做呢?我是否需要放置一个带有时间戳的隐藏字段并使用 ajax 来检查比这更晚的时间?