如何将加载gif添加到此脚本而不使其变为2页



我有一个简单的php脚本,可能需要15秒才能完成。我想添加一个加载gif,我更喜欢将其全部保存在一页上

我是一个相对的noob,我有一个php脚本,它根据传递给脚本的值执行多个任务。例如,在某个表单提交中,传递了一个值为"getSegments"的隐藏值"task",下面是来自getSegment任务的一些php

if ($task == 'getSegments') {
include('include/pre.content.php');
$response = [];
exec('/usr/bin/phantomjs phantomjstest.js', $response);
$data = $response[19];
// code that parses $data and builds $output
echo $output;
include('include/post.content.php');
}

从用户提交表单到返回并解析$response,可能需要长达15秒的时间。在此期间,添加"loading.gif"以显示最简单/最好的方法是什么?

我更喜欢将所有内容都保存在这个php脚本中,除了我可以将代码添加到我的css文件中,还有pre.content.php和post.contentphp,前者包含开始标记,包括结束head标记,后者包含我的页脚、版权、结束正文和html标记。

提前谢谢。

更新01-22-2019

根据Erik的建议,我创建了以下phantomtest.php文件进行测试:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" name="viewport">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<img src="images/loading3.gif" id="loading-gif">
<script>
$('#loading-gif').hide();
// $('#task_start_butt').click(function()
$(document).ready(function()
{
$('#loading-gif').show();
$.ajax({url:”pathTo getSegments.php"}).done(function(data){
$('#loading-gif').hide();
// display the result here
doSomethingOnComplete(data);
});
});
</script>
<?php
function doSomethingOnComplete($response)
{
// do here your work
$data = $response[19];
echo "Data = $data";
}
?>
</body>
</html>

和getSegments.php

<?php
$response = [];
exec('/usr/bin/phantomjs phantomjstest.js', $response);
$data = $response[19];
echo $data;
?>

我换了Erik的

$('#task_start_butt').click(function()

$(document).ready(function()

因为我希望当用户来自表单时,脚本在页面加载时启动。我认为脚本运行正常,因为每次运行phantomtest.php时,loading3.gif都会在预期范围内显示不同的时间,然后当ajax调用的getSegments.php完成时,它会被隐藏(我认为)。但是,我无法显示getSegments.hp.的输出

如果有人对如何做到这一点有什么建议,我将不胜感激。谢谢


我进一步更新并移动

function doSomethingOnComplete($response)

从php部分中取出,并将其放入脚本部分。我现在可以用输出数字11了

document.write(5 + 6);

所以现在我所需要的就是如何将getSegments.php的结果转换为phantomtest.php。

您可以使用ajax调用任务,并使用JS来显示/隐藏加载动画。

HTML/JS(假设jQuery):

<a href="#" id="task_start_butt">Start the task</a>
<img src="loading.gif" id="loading-gif">
<script>
$('#loading-gif').hide();
$('#task_start_butt').click(function()
{
$('#loading-gif').show();
$.ajax({url:"url to your php script"}).done(function(data){
$('#loading-gif').hide();
// display the result here
});
});
</script>

您还需要修改php以只返回您想要显示的数据。

它有效!!!

php:

$response = [];
exec('/usr/bin/phantomjs phantomjstest.js', $response);
echo json_encode($response[19]);

JS:

<img src="images/loading3.gif" id="loading-gif">
<script>
$('#loading-gif').hide();
//    $('#task_start_butt').click(function()
$(document).ready(function () {
$('#loading-gif').show();
$.ajax({url: "https://aajumpseat.com/dev/getSegments.php"}).done(function (data) {
$('#loading-gif').hide();

// display the result here
output = JSON.parse(data);
document.write(output);
});
});

最新更新