duanfu1945 2019-03-26 21:02
浏览 37

通过javascript和php刷新html

I'm trying to show a notifications counter updated upon javascript.

I have tried to use the following to refresh the html:

At the top of the page declaring the counter value (how many messages user has):

<?php
    $nc =  notificationCount($user_data['id']);
    $ng = $user_data['id'];
    if ($nc >= 1){
        $nstyle = 'style="display:block;"';
    } else {
        $nstyle = 'style="display:block;"';
    }
?>

Then the standard initial loading of the counter value that works properly:

<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>

In attempt to keep the counter refreshing every 5000 I tried the following, but it does not refresh despite the increase in value taking place.

<script>
    function checkNotification() {
        console.log(' each 5 second...');
        document.getElementById("nc").value =  "<?php echo $nc;?>";
    }
    var myVar = setInterval(checkNotification, 5000);
</script>
  • 写回答

2条回答 默认 最新

  • dtby67541 2019-03-26 21:12
    关注

    A PHP page returns a result to the client. Once the page returns its result, it's done. You can't have a PHP page return a result every so often. But, what you can do is call out to a PHP page (using AJAX) that returns the notification count at regular intervals using 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>

    </div>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料