【发布时间】:2014-05-14 12:17:07
【问题描述】:
我想让每个帖子在其作者上线时变为绿色。我已经尝试解决我的编码问题至少一个星期了!!!请帮帮我!
例如,如果有 3 个用户发布了一些内容:
而user1登录,会变成:
那么说user2也同时登录:
现在如果 user2 或 user1 退出,它会变回灰色。一切都是实时的 - 无需刷新。我想这样当我打开网站时,我可以立即看到谁在线,而不是等待 2 秒(在这种情况下)立即看到实时更新。
我还希望能够为帖子添加动态链接。有没有办法在 div 之前插入标签,这取决于用户是否登录?
我的尝试:
更新:
Status.php
header('Content-Type: application/json');
$array = array();
$res = mysql_query("SELECT * FROM `users` 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);
主页
$(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
if($.inArray(data) !== -1){ // if userid in the returned data array, set to online
$(this).css({background: 'green'});
//add a link here
} else{ // if not, set to offline
$(this).css({background: 'grey'});
alert($.inArray(data));
}
});
} else { // if no one is online, set all to offline
$('.status').css({background: 'grey'});
}
}
});
}, 2000);
});
CSS 样式
.status{ background: grey; }
一切似乎都开始工作了,但我无法让在线用户变绿。我尝试向阵列发出警报,但由于某种原因我收到“-1”警报。我该如何解决?
我尽量说清楚!非常感谢所有帮助!
【问题讨论】:
-
您将在每个
while()循环上覆盖$array['message']和$array['userId'],因此您将始终只有 1 个用户数据。您需要返回一个数组,然后在您的 ajax 成功中循环遍历该数组。 -
另外
<div class="status" id="user'.$user_id.'">'.$title.'</div>会导致多个divs 具有相同的id,其中ids 需要是唯一的,这样您的js 将无法正常工作。更改为类或添加data-属性。 -
我在我的问题中将 } 放在了错误的位置。我更新了我的问题。 div 是 while 循环的一部分,因此 id 会有所不同。如何返回一个数组?只需返回 json_encode($array);而不是回声?
-
如果用户有超过 1 个帖子,
ids 将不是唯一的,即。您的示例有 2 个user1的帖子,因此您将有 2 个id="user1",因为您使用的是user_id。我正在寻找答案,很快就会发布。 -
你应该使用 web sockets 来做这样的事情...... PHP 并不是我的专长,但我敢肯定有一些不错的实时框架类似于 socket.io