我已经建立了一个通知系统,它几乎工作。我只是有一点不太明白的地方。当来自朋友的新更新传入时,它会按预期打印新通知的数量,只有当用户发布两次时才会弹出num_rows 2。但如果用户再次发布它更新和替换2个新的通知号码回到1在div,因为我在ajax中使用html来替换。我的问题是,我如何更新div来获得结果的总数所以它是1,2,3,4等等而不是2,1,1,1,1。我不想用(1)更新来替换div中的新行数,只是添加到已经在里面的新更新的数量。
有点像facebook显示通知的数量。假设我的墙上有两个和一个朋友的帖子,那么我就会有3个……但目前它添加了最后一个新的num行,并返回到1。
AJAX<script type="text/javascript">
function loadIt() {
var notification_id="<?php echo $notification_id['notification_id'] ;?>"
var notification_id= window.localStorage.getItem ('lastId');
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id,
dataType:"json",
cache: false,
success: function(response){
if(response){
dataHandler;
if(response.num){
window.localStorage.setItem('lastId', response.notification_id);
var dataHandler = function(response){
var isDuplicate = false, storedData = window.localStorage.getItem ('lastId');
for (var i = 0; i < storedData.length; i++) {
if(storedData[i].indexOf(response) > -1){
isDuplicate = true;
}
}
if(!isDuplicate){
storedData.push(response);
}
};
if(response){
if(response.num){
$("#notif_actual_text-"+notification_id).prepend('<div id="notif_actual_text-'+response['notification_id']+'" class="notif_actual_text"><a href="'+response['notification_id']+'">'+response['notification_content']+' </a><br />'+response['notification_time']+'</div></nr>');
$("#mes").html(''+ response.num + '');
}
};
}
}
}
});
}
setInterval(loadIt, 10000);
PHP $json = array();
$com=mysqli_query($mysqli,"select notification_id,notification_content,notification_time from notifications where notification_id > '$id' AND notification_status=1 ");
echo mysqli_error($mysqli);
$num = mysqli_num_rows($com);
if($num!=1){
$json['num'] = $num;
}else{
$json['num'] = 0;
}
$resultArr = mysqli_fetch_array($com);
$json['notification_id'] = $resultArr['notification_id'];
$json['notification_content'] = $resultArr['notification_content'];
mysqli_free_result($com);
header('Content-Type: application/json');
echo json_encode($json);
}
客户端的通知数量为storedData.length.
所以我将替换计数器
$("#mes").html(''+ response.num + '');
$("#mes").html(storedData.length);