我遇到了一个问题,即php脚本永远不会因其工作而终止,因此它永远没有机会将数据传回ajax以html格式显示回用户。
为了更清楚,我要做的是让用户点击html页面上的按钮,该按钮执行一个javascript函数,该函数使用ajax来执行php脚本。php 脚本使用 popen 执行一个永无止境的命令(即:ping localhost),然后我回显 popen 的输出。问题是,因为 php 脚本永远不会完成,除非我杀死 ping 进程,否则永远不会报告回显,这会导致 php 脚本结束并且回显的数据返回到 javascript 函数以 html 显示。
我希望能够在 php 脚本运行时看到实时输出。如果我在 html 网站中单击该按钮,我希望该按钮调用 javascript 函数,然后执行 php 脚本,我希望在 php 脚本实时运行时立即看到每个回声。这可能吗?
这是我到目前为止的代码:
索引.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function execfunc() {
// Clear any previous output.
clearOutput();
$.ajax({
type: "GET",
url: "phpscript.php",
data: "",
success: function(msg){
$('#divOutput').html(msg);
}
}); // Ajax Call
}
function stopReadout() {
// to do
}
function clearOutput() {
$("#divOutput").html("");
}
</script>
</head>
<body>
<h3>Executing Linux Command</h3>
<p>Push the button to execute the command "ping localhost":</p>
<button type="button" onclick="execfunc();">Execute</button>
<button type="button" onclick="stopReadout();">Stop</button>
<button type="button" onclick="clearOutput();">Clear</button>
<br/>
<p id="label">Terminal output:</p>
<br/>
<div id="divOutput" style="width:800px;height:512px;border:1px solid black;overflow:scroll"></div>
</body>
phpscript.php
<?php
while (@ ob_end_flush()); // end all output buffers if any
$cmd = 'ping localhost';
$proc = popen($cmd, 'r');
echo '<pre>';
while (!feof($proc))
{
echo fread($proc, 4096);
flush();
}
echo '</pre>';
?>
如果您单独运行 phpscript.php,它工作正常并回显到浏览器窗口。但是如果我使用 ajax 从索引.html javascript 执行脚本,我不会得到任何实时输出,因为 php 脚本永远不会完成。
我什至尝试 phpscript.ph 制作一个 fifo 管道并将 ping 输出转储到 fifo 管道中,然后我有另一个 php 脚本回显回"cat fifofile",但同样的行为发生了。
任何建议或帮助将不胜感激!D
为此,您需要使用 Web 套接字。