[英]Refreshing html via javascript and php
我正在尝试在javascript上显示更新的通知计数器。
我试图使用以下内容刷新html:
在页面顶部声明计数器值(用户拥有的消息数):
<?php
$nc = notificationCount($user_data['id']);
$ng = $user_data['id'];
if ($nc >= 1){
$nstyle = 'style="display:block;"';
} else {
$nstyle = 'style="display:block;"';
}
?>
然后标准的初始加载计数器值正常工作:
<li id ="ndiv" class="nav-item pt8" <?php echo $nstyle; ?>><a href="javascript:void(0);" data-toggle="modal" data-target="#myModal" onclick="showUser(<?php echo $ng;?>)">
<i class="fa fa-bell f18 cr"></i><span id ="nc" class="f16 cr"><?php echo $nc;?></span></a>
</li>
为了保持计数器每5000次刷新我尝试了以下,但尽管价值增加,但它不会刷新。
<script>
function checkNotification() {
console.log(' each 5 second...');
document.getElementById("nc").value = "<?php echo $nc;?>";
}
var myVar = setInterval(checkNotification, 5000);
</script>
PHP页面将结果返回给客户端。 页面返回结果后,就完成了。 你不能让PHP页面经常返回结果。 但是,您可以做的是调用PHP页面( 使用AJAX ),该页面使用setInterval()
定期返回通知计数。
let notifications = document.getElementById("notifications"); // This would be a function that calls a .php page to get // the notification count returned. You could use AJAX // to make that call. function simulateServerCode(){ return Math.floor(Math.random() * 100); } let timer = setInterval(function(){ notifications.textContent = simulateServerCode(); }, 5000);
<div>You have <span id="notifications"></span> notifications.<div>
您不需要服务器端来显示通知。
尝试这个:
JS:
notificationsCount = document.getElementById("notificationsCount");
numberOfNotification = 10; // example
showing = setInterval(function(){
notificationsCount.textContent = numberOfNotificaton;
}, 5000);
HTML:
<h1>
Number of notifications <h1 id="notificationsCount"></h1>
</h1>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.