Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/248.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
js计数器不在php中显示_Php_Javascript_Counter - Fatal编程技术网

js计数器不在php中显示

js计数器不在php中显示,php,javascript,counter,Php,Javascript,Counter,我不明白为什么我没有看到div中的每一个数字 我的代码 <head> <script> function countit(i) { document.getElementById('counter').innerHTML = i; } </script> </head> <body> <div id="counter"></div

我不明白为什么我没有看到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>

函数countit(i)
{
document.getElementById('counter').innerHTML=i;
}
countit(1)
countit(2)
countit(3)
我有一个php脚本,它处理来自数据库的多条记录,我想显示一个计数器 正在处理的当前记录的。我以为JS就是这样做的。我看到了与上面推荐的代码非常相似的东西


如果您有任何见解,我们将不胜感激。

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

重写您的逻辑以使用一个


或者,在PHP脚本中,但请注意,这可能会影响浏览器缓存页面的能力

问题在于php代码在服务器上执行,而您需要在客户端(JavaScript)上执行代码才能工作:

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


</script>

var-idx=1;
var doCount=函数(){
如果(idx>=3)返回;
countit(idx);
设置超时(doCount,1000);
};
doCount();
删除以下内容:

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

countit(2)
countit(3)

PHP是服务器端语言,而Javascript是客户端语言。我猜您只是在
counter
div中看到了
3
。原因是PHP
sleep(1)
甚至在页面呈现之前就发生了。您需要在Javascript中使用
setInterval
,以完成您尝试执行的操作。

您的代码等待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>

函数countit(i)
{
document.getElementById('counter').innerHTML=i;
}
countit(1)
countit(2)
countit(3)
那可能不是你想要的。 让我们试试这样的方法:

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

    counter();
</script>

var i=1;
函数计数器()
{
if(i<4)
{
countit(i);
i++;
设置超时(计数器,1000);
}
}
计数器();

sleeps(睡眠)就在那里,所以我可以看到计数的变化。我想在php代码中的不同位置执行js函数,即:处理x个记录后,调用js函数并更新计数。我将研究禁用输出缓冲,看看这会把我引向何方。@user2076615:
从php代码的不同位置执行js函数。这样不行。PHP在浏览器看到JavaScript.ok之前运行。也许我对这件事的看法是错误的。如果我有一个php脚本,它正在处理一个大表,并且花费了相当长的时间(实际上是几分钟),那么我如何在页面上显示一个计数器,让用户知道它们在处理过程中的位置呢?AJAX是您需要使用的。这听起来像是我需要的。去研究。非常感谢。首先,您混合了服务器端和客户端脚本。这让你感到困惑。