現在,每次用戶登錄,該用戶所做的所有帖子都會變綠,而所有離線用戶的帖子都是灰色的。添加一個鏈接到一個在線用戶的div,並刪除在線
我想添加一個JavaScript函數的鏈接,當div爲綠色時,以及不同的鏈接爲灰色時。我在PHP中沒有問題,但我希望它能夠實時工作,就像沒有頁面刷新的顏色更改一樣。
的HTML
<div class="main_ads status" id="user'.$user_id.'">post</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[] = 'user'.$row['user_id']; // this adds each online user id to the array
}
}
echo json_encode($array);
Ajax代碼
$(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 = $(this).attr('id'); // get the user#
if($.inArray(userid, data) !== -1){ // if userid # in the returned data array set to online
$(this).css({background: '#40A547'});
} else{ // if not, set to offline
$(this).css({background: '#7f8c8d'});
}
});
} else { // if no one is online, set all to offline
$('.status').css({background: '#7f8c8d'});
}
}
});
}, 2000);
});
我苦思冥想的方式來做到這一點,並認爲分配一個變量與HTML標籤,將在線和離線不同,但不知道如何調用該變量從AJAX代碼到HTML。
所有幫助非常感謝!
看到這裏解決你不seing :)問題http://stackoverflow.com/questions/1570146/ajax-jquery-success-scope [ie ajax範圍] –
如果AJAX請求花費的時間超過2秒,那麼'setInterval()會發生什麼?...只是需要思考。 –
它只是用於測試。我會讓它15秒。 @UnamataSanatarai我在那裏得到邏輯,但我沒有真正得到它的工作方式。我創建了一個var,它等於我想要的鏈接,並將其作爲.siblings('。status')。html(new); ('新'是鏈接) – Gadgetster