Js计数器在php中不显示

js counter not displaying in php

本文关键字:显示 php 计数器 Js      更新时间:2023-09-26

我不明白为什么我没有看到div中显示的每个数字。

我的代码…

<head>
    <script>
        function countit(i)
        {
            document.getElementById('counter').innerHTML = i;
        }
    </script>
</head>
<body>
<div id="counter"></div>
<script>countit(1)</script>
<?php sleep(1); ?>
<script>countit(2)</script>
<?php sleep(1); ?>
<script>countit(3)</script>
</body>

我有一个php脚本,从数据库中处理几条记录,我想显示一个计数器正在处理的当前记录的。我认为JS是实现这一目标的方法。我在so.

上看到了与上面推荐的代码非常相似的代码。

PHP缓冲输出,直到页面运行完毕才发送页面。在执行脚本元素之间不运行休眠。

重写你的逻辑,使用JavaScript的setInterval代替。

或者,禁用或避免PHP脚本中的输出缓冲,但请注意,这可能会影响浏览器缓存页面的能力。

PHP是服务器端语言,而Javascript是客户端语言。我猜你只是看到3在你的counterdiv。原因是因为PHP sleep(1)发生在页面甚至呈现之前。你需要在Javascript中使用setInterval来完成你想做的事情。

问题是你的php代码在服务器上执行,而你需要在客户端(JavaScript)上执行代码来工作:

<script>
  var idx = 1;
  var doCount= function(){
      if(idx >= 3) return;
      countit(idx);
      setTimeout(doCount,1000);         
  };
  doCount();

</script>

删除以下内容:

<?php sleep(1); ?>
<script>countit(2)</script>
<?php sleep(1); ?>
<script>countit(3)</script>

您的代码等待2秒,浏览器接收到:

<head>
    <script>
        function countit(i)
        {
            document.getElementById('counter').innerHTML = i;
        }
    </script>
</head>
<body>
<div id="counter"></div>
<script>countit(1)</script>
<script>countit(2)</script>
<script>countit(3)</script>
</body>

那可能不是你想要的。让我们试试这样做:

<script>
    var i = 1;
    function counter()
    {
       if (i < 4)
       {
         countit(i);
         i++;
         window.setTimeout(counter,1000);
       }
    }
    counter();
</script>