0

我有一个我正在处理的 WOL PHP 脚本,我希望找到一种方法来使用 ajax 刷新页面的一部分,或者我是否应该调用外部 php 脚本?

我的 PHP 脚本启动了一台电脑,然后多次检查它是否已启动并运行....但是,对于 PHP,用户显然必须等到它完全完成才能显示结果,我希望那里是一种让我正在运行的“while 循环”在页面的第一部分加载后运行和更新的方法吗?

本质上,checkstatus 函数检查端口是否正在运行,然后显示输出。我希望加载主页,然后使用 ajax 或其他 php 脚本更新端口检查的状态?不知道怎么做。

function CheckStatus($tries, $device, $deviceip, $deviceport, $devicemac1, $devicemac2, $maxtries, $broadcast, $udport, $timeout){
    while($tries <= $maxtries){
        echo "<br \>";
        echo "Try $tries of $maxtries";
        echo "<br \>";
        //echo portcheck($deviceip, $deviceport);
        if (portcheck($deviceip, $deviceport) != 0){
                echo "  ------>  Could NOT open connection to $device at $deviceip on port $deviceport";
                echo "<br \>";                
                //echo "<br /> TRIES: $tries";

            }else{
                echo "<br \>";
                echo "<br \>";
                echo "<br \>";
                echo "TESTED OKAY!  $device";
                return TRUE;
            }
            $tries=$tries + 1;
    }
    echo "<br />";
    echo "MAX TRIES REACHED... COULD NOT CONNECT!";
    return FALSE;
}   
4

1 回答 1

0

发表评论说“你不能在单个 PHP 实例中做到这一点”,我现在继续证明自己错了。

可以使用某种服务器推送设置来做到这一点。考虑以下代码:

<?php

  // Do all your preliminary stuff here

?>
<html>
  <head>
    <title>Server push demo</title>
    <script type="text/javascript">
      function updateTries(tries) {
        document.getElementById('num_tries').innerHTML = tries;
      }
      function pushEvent(str) {
        var event = document.createElement('div');
        event.innerHTML = str;
        document.getElementById('stream_container').appendChild(event);
      }
    </script>
  </head>
  <body>
    <div>
      Number of tries:
      <span id="num_tries"></span>
    </div>
    <div id="stream_container"></div>
<?php

  // Push all output so far to the client
  flush();

  // Start status check loop
  CheckStatus($tries, $device, $deviceip, $deviceport, $devicemac1, $devicemac2, $maxtries, $broadcast, $udport, $timeout);

  function CheckStatus($tries, $device, $deviceip, $deviceport, $devicemac1, $devicemac2, $maxtries, $broadcast, $udport, $timeout){

    while ($tries < $maxtries) {

        echo "<script type='text/javascript'>updateTries($tries);</script>";
        flush();

        if (portcheck($deviceip, $deviceport) != 0){

          echo "<script type='text/javascript'>pushEvent('Could NOT open connection to $device at $deviceip on port $deviceport');</script>";
          flush();

        } else {

          echo "<script type='text/javascript'>pushEvent('TESTED OKAY! $device');</script>";
          flush();
          return TRUE;

        }

        $tries++;

    }

    echo "<script type='text/javascript'>pushEvent('MAX TRIES REACHED... COULD NOT CONNECT!');</script>";
    flush();
    return FALSE;

  }

?>
</body></html>

但是,我仍然认为最好将循环抽象到客户端并使用 AJAX 轮询服务器,服务器一次执行一项检查。

于 2012-05-15T19:13:43.140 回答