我正在尝试在菜单上创建动态数量的通知提要。当我的其中一个SQL表中有新添加的数据时,它会自动更改通知栏上的编号,而不会刷新页面。
下面是html:
<li>
<a href="categories.php">
Categories
<span class="badge" id="badg"></span>
</a>
</li>
下面是我使用的脚本:
$(document).ready(function() {
var arr = <?php include("array.php"); ?>; /* e.g. ["1","2","3"] */
var size = arr.length;
document.getElementById('badg').innerHTML = size;
});
显示了数组的数量,但不会在有新数据时自动更改。只有当用户刷新页面时,它才会更改。
我怎样才能自动完成?
发布于 2015-03-26 16:18:12
您必须在jquery的setInterval函数中使用ajax,作为对ajax文件的响应,发送更新的通知计数,然后按计数更新跨度。
像这样的东西
<script>
$(document).ready(function() {
setInterval(function() {
//ajax content
}, 5000);
});
</script>
发布于 2015-03-26 16:19:15
您好,您需要使用"set_timeout“检查是否有新的通知数据。下面是一个示例:
<script>
$(document).ready(function() {
update_notification()
});
function update_notification() {
$.post('get_notification.php',{},
function(e) {
$("span#notif_number").html(e.count);
}, 'JSON'
);
setTimeout(function() {
update_notification();
}, 2000); //displays every 3 sec
}
</script>
<div>Notifications(<span id="notif_number">0</span>)</div><br/>
接下来,创建一个新页面,名称为"get_notification.php“,并放入以下代码:
<?php
//ignore this section. This is only to prove that the notification number is updating
$count = rand(1,10);
$data = array();
for($a = 0; $a>=$count; $a++) {
$_data = new stdClass();
$_data->id = $a;
$_data->name = "item".$a;
array($data, $_data);
}
//end
//########### YOUR CODE here#################
// MySQL code here
// $data = mysql script with data content;
// $count = count($data);
echo json_encode(array("data"=> $data, "count"=>$count));
?>
发布于 2015-03-26 10:24:17
看看这个https://github.com/SeanOC/jquery.comet你正在尝试做一些像Gmail通知或Facebook Messenger做的事情
https://stackoverflow.com/questions/29269831
复制相似问题