javascript中的setInterval php变量


setInterval php variable in javascript

我正试图在我的网站上发布一个更新的ping,而不需要一直重新加载,但当我尝试它发布初始ping时,它在我设置的时间间隔后没有更新

index.php:

<script>
    setInterval(document.write('<?php echo json_encode(getPingout());?>'),100);
</script>

functions.hp:

    <?php    
    function getPingout() {
            // some function that finds the ping of the server
        return $server->getPing();
    }
?>

不能在页面加载后让php多次运行。该PHP在页面加载时执行一次。

要执行您尝试执行的操作,您应该使用一些javascript和ajax调用。

$(function(){
   function pingServer(){
     $.post('/ping.php',function(data){
       console.log('server is ok');
     });
   }
   setInterval( pingServer, 4000 );
});

此外,您可能不需要每隔100次对服务器进行ping。否则,您可能会遇到问题。

javascript&PHP协同工作。

为了在不重新加载页面的情况下刷新数据,必须异步请求数据。搜索AJAX或XHR,我真的建议你研究像jQuery这样的东西,因为与你自己编写javascript相比,你会节省很多编写代码和调试的时间。

如果你在jQuery:中这样做

//this means run when page is ready
$(function(){
  setInterval(function(){
      //Send POST request to ping.php
      $.post('ping.php',{},function(){
        //Append the result to the body in a new div
        $('body').append($('<div>'+data+'</div>'));
      });
  },100);
});

而你的ping.php应该只返回ping而不返回其他内容。

不要让美元符号混淆你,在PHP中,它是变量的前缀,但在javascript/jquery上下文中,它只是一个变量,包含你从中调用函数的jquery对象。