为了尝试后台测试,我创建了3个文件:
Index.html (负责通过ajax调用php文件)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Background Task Manager</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
Press The Button To execute a Background Task...
<br>
<button id="perform">Perform Task</button>
</body>
<script>
$( document ).ready(function() {
$( "#perform" ).click(function() {
submitAjax();
});
function submitAjax() {
$.ajax({
url: 'test.php',
type: "post",
data: '',
success: function (data) {
alert(data);
}
});
}
});
</script>
</html>
Test.php (使用后台方法调用另一个文件的文件)
<?php
//Perform Background Task
exec("C:/wamp/bin/php/php5.6.35/php.exe C:/wamp/www/background/file.php");
echo "Process Started";
?>
File.php (将在后台执行的文件)
<?php
//Create a File
sleep(20);
$content = "My Text File";
$fp = fopen("myText.txt","wb");
fwrite($fp,$content);
fclose($fp);
echo "File Created...";
?>
的想法如下:一旦用户单击按钮,就会向test.php文件发出一个请求。test.php将触发对file.php的后台请求,消息('Process Started')将立即出现,20秒后将在我的项目文件夹中创建一个文件。
正在发生什么:当用户单击按钮时,我只在20秒后收到消息'Process Started‘,即请求不是在后台模式下发出的。
我希望发生的事情:当用户点击按钮时,消息‘进程已启动’将立即出现,20秒后,php将在我的项目的文件夹中创建文件。
我该如何解决这个问题?
发布于 2018-06-15 06:39:06
尝试更改:
exec("C:/wamp/bin/php/php5.6.35/php.exe C:/wamp/www/background/file.php");
echo "Process Started";
至:
ob_start();
echo "Process Started";
ob_end_flush();
ob_flush();
flush();
exec("C:/wamp/bin/php/php5.6.35/php.exe C:/wamp/www/background/file.php");
您问题的相关答案:continue processing php after sending http response
您也可以不使用exec()
而使用include
,它将如下所示:
start();
echo "Process Started";
ob_end_flush();
ob_flush();
flush();
include 'background/file.php';
因此您可以更轻松地调试file.php
发布于 2018-06-15 07:09:00
为什么要从php调用exec来运行php shell?这没有任何意义。为什么不直接调用file.php呢?
回显位于ajax调用中,因此不会被看到;它将作为页面输出返回。通常,对于这样的情况,您需要使用一个字段:
<?
<p class="Message"></p>
<button onclick="foo()">Click Me</button>
<script>
function foo(){
$('.Message').text('Processing.....');
$.post('file.php',function(ret){
// ret should tell us what happened
if (ret == "ok")
$('.Message').text('File Created');
else
$('.Message').text('File Not Created. Something Went Wrong');
});
}
</script>
file.php应该创建文件,测试文件是否已创建,并返回一个可以测试的值,以查看操作是否成功。您还可以在console.log中检查ret,以查看是否出现任何语法错误或异常。页面上的任何输出都将被返回,因此您可能得不到干净的响应。最好让file.php回显一些东西:
if ($file_created)
echo "ok";
else
echo "failed";
https://stackoverflow.com/questions/50866646
复制相似问题