【发布时间】: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