【问题标题】:setInterval php variable in javascript [duplicate]javascript中的setInterval php变量[重复]
【发布时间】:2014-04-29 16:39:19
【问题描述】:

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

index.php:

<script>

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

functions.php:

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

【问题讨论】:

  • 了解页面生命周期。
  • 致选择正确答案的模组:w3schools.com?说真的,对于这个关于堆栈溢出的家伙,没有比参考网络开发的伏地魔更好的解释了吗?

标签: javascript php variables combinations setinterval


【解决方案1】:

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

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

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

   setInterval( pingServer, 4000 );
});

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

【讨论】:

  • 我发现这对我来说是最简单的方法
  • @user3586172 所以赞成这个答案并接受它。
【解决方案2】:

这不是 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 对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    • 2015-05-11
    • 2013-10-28
    相关资源
    最近更新 更多