Haf*_*tab 1 php mysql ajax session jquery
请告诉我如何通过访问其会话来显示用户在线或离线.这是php和mysql查询
header('Content-Type: application/json');
$array = array();
$res = mysql_query("SELECT * FROM `posts` WHERE status=1");
if(mysql_num_rows($res) > 0){
while($row = mysql_fetch_assoc($res)){
$array[] = $row['user_id']; // this adds each online user id to the array
}
}
echo json_encode($array);Run Code Online (Sandbox Code Playgroud)
我试试这段代码这是js文件
<script type="text/javascript">
$(document).ready(function() {
setInterval(function(){
$.ajax({
url: 'status.php',
dataType: "json",
type: 'GET',
success: function(data) {
if (data.length > 0){ // if at least 1 is online
$('.status').each(function(){ // loop through each of the user posts
var userid = parseInt($(this).attr('id').replace('user','')); // get just the userid #
if($.inArray(userid, data) !== -1){ // if userid # in the returned data array set to online
$(this).css({background: 'green'});
} else{ // else if userid # not in the returned data array set to offline
$(this).css({background: 'grey'});
}
});
}
else { // if no one is online, set all to offline
$('.status').css({background: 'grey'});
}
}
});
}, 2000); //2s just for testing. Set to 15s when code fully works.
});
</script>Run Code Online (Sandbox Code Playgroud)
但是这个代码不是根据我的重新运行而根据我在数据库中保存的数据运行每次我在DB中保存我的状态然后在这个行为上它给我结果. 我想要的是
2.如果用户维持其会话,则其状态为在线
没有直接做到这一点afaik.没有正确的方法来检测用户是否已关闭其浏览器.我见过的一种常用于在[上下文]中解决这个特定问题的方法是使用表last_activity_timestamp中的posts字段.每次用户进行任何活动时,last_activity_timestamp都会使用新时间进行更新.
$res = mysql_query("UPDATE `posts` SET last_update_timestamp = NOW() WHERE user_id = {$currentUserId};");
Run Code Online (Sandbox Code Playgroud)
然后在您的代码中检查用户当前是否在线,您还可以检查自用户上次活动以来是否已经过了某个时间段(例如20分钟),如下所示:
$res = mysql_query("SELECT * FROM `posts` WHERE status=1 AND TIMESTAMPDIFF(MINUTE, last_activity_timestamp, NOW()) > 20;");
Run Code Online (Sandbox Code Playgroud)
如果用户的最后一项活动超过20分钟,那么他就会被有效注销.
| 归档时间: |
|
| 查看次数: |
14488 次 |
| 最近记录: |