【问题标题】:Update page content from live PHP and Python output using Ajax使用 Ajax 从实时 PHP 和 Python 输出更新页面内容
【发布时间】:2017-09-12 19:48:48
【问题描述】:

老用户,第一次提问。我从社区学到了很多东西,我喜欢这个网站。

这就是我的目标。我想要一个在后端运行 ping 命令的 Web 界面。理想情况下,我想要一个网站,它有一个允许您输入 IP 地址或域的文本输入、一个运行命令的按钮和一个从 PHP 运行以实际运行 ping 命令的 python 脚本。棘手的部分是让输出在命令行上输出时实时打印到网站。我想这样做是为了让这个概念适应未来并最终使用不同的 iperf 参数。

我构建了一个“技术上”完成工作的 PHP 小页面,但我不知道如何仅在单击按钮时调用 PHP 脚本。因为它是一个 PHP 页面,所以它会在页面加载时运行。所以经过一些研究,我认为 ajax jquery 是我正在寻找的。我花了大约 2 天时间尝试不同的事情,让我非常接近,但似乎我正在围绕我的解决方案跳舞。

根据我对 ajax 的了解,我基本上需要一个按钮来运行链接到我的工作 php 脚本的 ajax 函数。我可以让它运行脚本,但我不能让它以实时/连续的方式更新页面内容。仅当命令完成运行时。

这是我的 php 页面,它执行它需要执行的操作,但每次加载/重新加载页面时都会执行此操作。不理想。我希望脚本仅在按下按钮时运行。

liveping.php:

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>
	<form action="liveping.php" id="ping" method="post" name="ping">
		Domain/IP Address: <input name="domain" type="text"> <input name="ping" type="submit" value="Ping">
	</form><?php

	if (isset($_POST['ping'])) {
	  function liveExecuteCommand($cmd)
	  {
	      while (@ ob_end_flush()); // end all output buffers if any

	      $proc = popen("$cmd 2>&1", 'r');

	      $live_output     = "";
	      $complete_output = "";

	      while (!feof($proc))
	      {
	          $live_output     = fread($proc, 4096);
	          $complete_output = $complete_output . $live_output;
	          echo "<pre>$live_output</pre>";
	          @ flush();
	      }

	      pclose($proc);
	  }
	}

	$domain =  $_POST['domain'];

	$pingCmd = "python /var/www/html/ping.py ".$domain;

	if (isset($_POST['ping'])) {
	  liveExecuteCommand($pingCmd);
	}

	?>
</body>
</html>

ping.py:

#!/usr/bin/python
import cgi
import os
import sys
ping = "ping -c 5 -W 2 "+sys.argv[1]
os.system(ping)

我尝试过的一些事情:

<html>
    <head>
        <script>
        var ajax = new XMLHttpRequest();
        ajax.onreadystatechange = setInterval(function() {
            if (ajax.readyState == 4) {
                document.getElementById('content').innerHTML = ajax.responseText;
            }
        },100);
        function updateText() {
            ajax.open('GET', 'ajax.php');
            ajax.send();
        }
        </script>
    </head>
    <body>
        <button onclick="updateText()">Click Me</button>
        <div id="content">Nothing here yet.</div>
    </body>
</html>
或者

<!DOCTYPE html>
<html>
	<body>
		<head>
			<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>

			<script type="text/javascript">
			   var auto_refresh = setInterval(
			      function ()
			      {
			         $('#load_tweets').load('ajax.php').fadeIn("slow");
			      }, 1000); // refresh every 10000 milliseconds
			</script>

		</head>

     <div id="load_tweets"> </div>
	
	</body>
</html>

使用 ajax.php

<?php
while (@ ob_end_flush()); // end all output buffers if any

$proc = popen("ping -c 5 -W 2 google.com", 'r');

$live_output     = "";
$complete_output = "";

while (!feof($proc))
{
    $live_output     = fread($proc, 4096);
    $complete_output = $complete_output . $live_output;
    echo "<pre>$live_output</pre>";
    @ flush();
}

pclose($proc);
?>

感谢您的帮助!

【问题讨论】:

    标签: javascript php jquery python ajax


    【解决方案1】:

    您不需要 python 来显示 ping 结果。只需两个 PHP 文件就足够了。

    1. index.php 将具有 AJAX 功能以及表单。
    2. ajax.php 将具有 ping 指定域地址的代码。

    我担心使用 jQuery 你可能无法捕捉到实时提要。因为它没有任何onreadystatechange。因此,在这种情况下,您可能需要使用 vanilla JavaScript。这是一个工作演示:

    index.php:

    <!DOCTYPE html>
    <html>
    <head>
        <title>Ping AJAX</title>
    </head>
    <body>
        <div>
            Domain/IP Address: <input id="domain" type="text"> 
            <input id="ping" type="button" value="Ping">
        </div>
        <div id="result"></div>
        <script>
            function updateText(domain) {
                var ajax = new XMLHttpRequest();
                  ajax.onreadystatechange = function() {
                    if (this.readyState == 3) {
                      var old_value = document.getElementById("result").innerHTML; 
                      document.getElementById("result").innerHTML = this.responseText;
                    }               
                };          
                var url = 'ajax.php?domain='+domain;
                ajax.open('GET', url,true);
                ajax.send();
            }
            document.getElementById("ping").onclick = function(){
                domain = document.getElementById("domain").value;
                updateText(domain);
            }
        </script>
    </body>
    </html>
    

    ajax.php:

    <?php
    if (isset($_GET['domain'])) {
        function liveExecuteCommand($cmd)
        {
            while (@ ob_end_flush()); // end all output buffers if any
    
            $proc = popen($cmd, 'r');
    
            $live_output     = "";
            $complete_output = "";
    
            while (!feof($proc))
            {
                $live_output     = fread($proc, 4096);
                $complete_output = $complete_output . $live_output;
                echo "<pre>$live_output</pre>";
                @ flush();
            }
    
            pclose($proc);
        }   
        $domain =  $_GET['domain'];
        $pingCmd = "ping ".$domain;
        liveExecuteCommand($pingCmd);
    }
    else{
        echo "No post request";
    }
    ?>
    

    输出:

    声明:

    由于我当前使用的是 Windows 操作系统,因此更改了 ping 命令。根据您的操作系统更新它。

    作为第一次提问的你,你把问题描述得很清楚,也表现出你为解决问题所做的努力。我真的很感激。

    【讨论】:

    • 这个解决方案对我有用!感谢您的快速和彻底的回复!另外,感谢您使用 Python 脚本指出我的冗余。少一件事要处理。
    【解决方案2】:
    ajax.readyState == 4
    

    基本上意味着,另一边的脚本已经完成...... 3是部分的。

    https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState

    【讨论】:

      【解决方案3】:

      您只需将所有 ajax 脚本放入函数中

      示例:

      function updateText() {
              $.ajax({
                type: 'GET', // can be POST, too
                url: "ajax.php",
                crossDomain: true,
                data: {
                      firstvar: firstvar,
                      secondvar: secondvar
                  },
                cache: false,
                success: function(data) {
      
                  if($.trim(data) == "false") {
                      alert("Fail to recived data");
                  }
                  else {
                      // Success getting data
                      // Do some jobs
                  }
      
                }
              });
          }
      

      如果要取消提交不刷新,可以使用

      return false; // At the end of the function above
      

      希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 2016-04-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多