使用Ajax从实时PHP和Python输出更新页面内容 [英] Update page content from live PHP and Python output using Ajax

查看:60
本文介绍了使用Ajax从实时PHP和Python输出更新页面内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

长期用户,首次提问。我从社区学到了很多,我喜欢这个网站。



所以这就是我要拍摄的内容。我希望有一个在后端运行ping命令的Web界面。理想情况下,我希望网站具有允许您输入IP地址或域的文本输入,运行该命令的按钮以及从PHP运行以实际运行ping命令的python脚本。棘手的部分是将输出打印到网站上,因为它是在命令行输出的。我想以这种方式做到这一点,作为一种未来证明概念的方法,并最终使用不同的iperf参数。



我构建了一个技术上完成工作的小PHP页面,但我无法弄清楚如何在单击按钮时调用PHP脚本。因为它是一个PHP页面,所以只要加载页面就会运行它。经过一些研究,我认为ajax jquery是我正在寻找的。我花了大约2天的时间尝试不同的东西让我非常接近,但似乎我在我的解决方案中跳舞。



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



这是我的php页面,它可以执行它需要做的事情,但每次加载/重新加载页面时都会这样做。不理想。我希望脚本只在按下按钮时运行。



liveping.php:

 <!DOCTYPE html>< ; HTML>< HEAD> <标题>< /标题>< /头><身体GT; < form action =liveping.phpid =pingmethod =postname =ping>域/ IP地址:< input name =domaintype =text> < input name =pingtype =submitvalue =Ping> < / form><?php if(isset($ _ POST ['ping'])){function liveExecuteCommand($ cmd){while(@ ob_end_flush()); //结束所有输出缓冲区,如果有任何$ 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 / pythonimport cgiimport osimport sysping =ping -c 5 -W 2+ sys.argv [1] os.system(ping) 






我尝试过的一些事情:



 < html> < HEAD> <脚本> 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> < /头> <身体GT; < button onclick =updateText()>点击我< / button> < div id =content>此处尚无。< / div> < / body>< / html>  


OR



 <!DOCTYPE html>< html> <身体GT; < HEAD> < script type =text / javascriptsrc =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); //刷新每10000毫秒< / script> < /头> < div id =load_tweets> < / DIV> < / body>< / html>  



with ajax。 php



 <?phpwhile(@ ob_end_flush()); //结束所有输出缓冲区,如果有任何$ 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);?>  



<感谢您的帮助!

解决方案

您不需要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>
域/ IP地址:< input id =domaintype =text>
< input id =pingtype =buttonvalue =Ping>
< / div>
< div id =result>< / div>
< script>
函数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()); //结束所有输出缓冲区,如果有任何

$ 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 {
echoNo post request;
}
?>

输出:





声明:



ping命令已更改,因为我当前正在使用Windows操作系统。根据您的操作系统更新它。



作为第一次提问者,您已经巧妙地描述了问题并且还展示了您为解决问题所做的努力。我真的很感激。


Long-time user, first-time asker. I've learned so much from the community and I love this site.

So here is what I'm shooting for. I want to have a web interface that runs ping commands on the backend. I ideally want a website that has a text input that allows you to enter an IP address or domain, a button that runs the command and a python script that runs from PHP to actually run the ping command. The tricky part for was to get the output to print to the website live as it is outputted on the command line. I want to do it this way as a way to future-proof the concept and eventually use different iperf parameters.

I built a little PHP page that "technically" gets the job done but I can't figure out how to only call the PHP script when the button is clicked. Since it's a PHP page, it runs whenever the page is loaded. So after some research, I figure ajax jquery is what I'm looking for. I've spent about 2 days trying different things that get me really close but it seems that I'm dancing around my solution.

From what I've learned about ajax, I essentially need a button that runs an ajax function that is linked to my working php script. I can get it to run the script but I can't get it to update the page content in a live/continuous manner. Only when the command is finished running.

Here is my php page that does what it needs to do but does it everytime the page is loaded/reloaded. Not ideal. I want the script to only run when the button is pressed.

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)


Some things I've tried:

<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>

OR

<!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>

WITH 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);
?>

Thanks for any help!

解决方案

You do not need python for showing ping results. Just two PHP files will be enough.

  1. index.php will have the AJAX functionalities along with the form.
  2. ajax.php will have the code to ping specified domain address.

I afraid that using jQuery you might not able to catch the live feed. Because it doesn't have any onreadystatechange. So, you might need to use vanilla JavaScript in this case. Here is a working demonstration:

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";
}
?>

Output:

Declaimer:

The ping command is changed as I am currently using Windows operating system. Update it according to your operating system.

As a first time questioner, you have described the problem neatly and also showed your efforts to solve the problem. I really appreciate it.

这篇关于使用Ajax从实时PHP和Python输出更新页面内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆