在 PHP 执行时加载页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17374535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Load page while PHP is executing
提问by tyler
What Im trying to do: Display a loading gif or text... at the very least show a black screen before and during the time the php is being executed.
我想做什么: 显示正在加载的 gif 或文本...至少在执行 php 之前和期间显示黑屏。
What I have tried.
我尝试过的。
I have tested using flush () and I get nothing until the entire php process is finished. I dont particularly like this concept either but I'll take anything.
我已经使用flush()进行了测试,在整个php进程完成之前我什么也没有得到。我也不是特别喜欢这个概念,但我会接受任何东西。
I am considering using two pages to accomplish this though the current project is nearly complete and would take some time to consolidate the scattered html/php code.
我正在考虑使用两个页面来完成此任务,尽管当前项目已接近完成并且需要一些时间来整合分散的 html/php 代码。
Currently I'm doing 3-simpleXML_load_file(), 1-include(), 1-file_get_contents() I have javascript function plotting data from one of the simpleXML_Load_file()...
目前我正在做 3-simpleXML_load_file(), 1-include(), 1-file_get_contents() 我有 javascript 函数从 simpleXML_Load_file() 之一绘制数据...
Im up for moving parts of the code to a different file but it's a big task. So id like some advise or suggestions on how to proceed.
我准备将部分代码移动到不同的文件,但这是一项艰巨的任务。所以我喜欢一些关于如何进行的建议或建议。
If I need to elaborate more just ask!
如果我需要详细说明,请问!
Thanks, JT
谢谢,JT
<html>
<head>
<?php
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
$weather_hourly = simplexml_load_file('http:....lat='.$lat.'&lon='.$long.'');
?>
<script type="text/javascript">
<!--Plot function-->
$(function()
{
var d =
[
<?php
//Pulling in hourly data to plot temp vs time
$i=0;
$array=array();
while ($i<=100)
{
echo '['. (strtotime($weather_hourly->data->{'time-layout'}->{'start-valid-time'}[$i])*1000) .','.$weather_hourly->data->parameters->temperature->value[$i] .'],';
$value = $weather_hourly->data->parameters->temperature->value[$i];
array_push($array,$value);
$i++;
}
foreach ($array as $key => $value)
{
$value = (string) $value;
$min_sec_array[] = $value;
}
?>
</script>
</head>
<body>
<div id=graph>
</div>
</body
回答by Seth
The main way you can accomplish this is by using AJAX and multiple pages. To accomplish this, the first page should not do any of the processing, just put the loading image here. Next, make an AJAX request, and once the request is finished, you can show the results on the page or redirect to a different page.
实现此目的的主要方法是使用 AJAX 和多个页面。为此,第一页不应该做任何处理,只需将加载图像放在这里。接下来,发出 AJAX 请求,请求完成后,您可以在页面上显示结果或重定向到其他页面。
Example:
例子:
File 1 (jQuery must be included also), put this in the body along with the loader animation:
文件 1(还必须包含 jQuery),将其与加载器动画一起放入主体中:
<script language="javascript" type="text/javascript">
$(function(){
var mydata = {};
$.post('/myajaxfile.php', mydata, function(resp){
// process response here or redirect page
}, 'json');
});
</script>
Update: Here is a more complete example based on your code. This has not been tested and needs to have the jQuery library included, but this should give you a good idea:
更新:这是基于您的代码的更完整示例。这尚未经过测试,需要包含 jQuery 库,但这应该给你一个好主意:
File 1: file1.html
文件 1:file1.html
</head>
<body>
<?php
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
?>
<!-- Include jQuery here! Also have the loading animation here. -->
<script type="text/javascript">
$(function(){
$.get('/file2.php?Lat=<?php echo $lat; ?>&Lon=<?php echo $long; ?>', null, function(resp){
// resp will have the data from file2.php
console.log(resp);
console.log(resp['min_sec_array']);
console.log(resp['main']);
// here is where you will setup the graph
// with the data loaded
<!--Plot function-->
}, 'json');
});
</script>
<div id=graph>
</div>
</body
</html>
File 2: file2.php I'm not sure if you needed the $min_sec_array, but I had this example return that as well as the main data you were using before.
文件 2:file2.php 我不确定您是否需要 $min_sec_array,但是我让这个示例返回了它以及您之前使用的主要数据。
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
$weather_hourly = simplexml_load_file('http:....lat='.$lat.'&lon='.$long.'');
//Pulling in hourly data to plot temp vs time
$i=0;
$main = array();
$array=array();
while ($i<=100)
{
$main[] = array((strtotime($weather_hourly->data->{'time-layout'}->{'start-valid-time'}[$i])*1000), $weather_hourly->data->parameters->temperature->value[$i]);
$value = $weather_hourly->data->parameters->temperature->value[$i];
array_push($array,$value);
$i++;
}
foreach ($array as $key => $value)
{
$min_sec_array[] = (string) $value;
}
echo json_encode(array(
'min_sec_array' =>$min_sec_array,
'main' => $main
));
exit();
?>
回答by sailingthoms
I would recommend not to do this with plain html and php if u expect it modify the page after it is loaded. Because php is server side processing, so it is executed before the page is send to the user. U need Javascript. Using Javascript will enable u to dynamically add or remove html elements to or from the DOM tree after the page was send to the user. It is executed by the users browser.
如果您希望它在加载后修改页面,我建议不要使用纯 html 和 php 执行此操作。因为php是服务器端处理,所以在页面发送给用户之前执行。你需要Javascript。使用 Javascript 将使您能够在页面发送给用户后动态地在 DOM 树中添加或删除 html 元素。它由用户浏览器执行。
For easier start I would recommend jQuery, because there are lots of tutorials on such topics.
为了更容易开始,我会推荐 jQuery,因为有很多关于此类主题的教程。
A small example:
一个小例子:
HTML
HTML
<head>
<meta charset="utf-8" />
<title> </title>
<script type="text/javascript" src="js/lib/jquery-1.9.1.js"></script>
</head>
<body>
<h1>Addition</h1>
<div id="error_msg"> </div>
<div id="content">
<!-- show loading image when opening the page -->
<img src="images/loading.gif"/>
</div>
<script type="text/javascript">
// your script to load content from php goes here
</script>
</body>
this will be nothing more then the following until now:
到目前为止,这仅是以下内容:
adding the following php file
添加以下php文件
<?php
$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
$result = $num1 + $num2;
echo '<p>Calculating '.$num1.' + '.$num2.' took a lot of time, but finally we were able to evaluate it to '.$result.'.</p>'
.'<p> '.$num1.' + '.$num2.' = '.$result.'</p>';
?>
wont change anything of the html, but adding javascript/ Jquery inside the HTML will be kind of connection between static html and server side php.
不会改变任何 html,但在 HTML 中添加 javascript/Jquery 将是静态 html 和服务器端 php 之间的一种连接。
$(document).ready(function(){
$.ajax({ // call php script
url: 'php/script.php?num1=258&num2=121',
type:'GET',
timeout: 500,
contentType: 'html'
}).success(function(data){
// remove loading image and add content received from php
$('div#content').html(data);
}).error(function(jqXHR, textStatus, errorThrown){
// in case something went wrong, show error
$('div#error_msg').append('Sorry, something went wrong: ' + textStatus + ' (' + errorThrown + ')');
});
});
This will change your page to show the loading animation until the php script returns its data, like:
这将更改您的页面以显示加载动画,直到 php 脚本返回其数据,例如:
So you can setup the whole page in plain html, add some loading gifs, call several php scripts and change the content without reloading the page itself.
因此,您可以在纯 html 中设置整个页面,添加一些加载 gif,调用多个 php 脚本并更改内容,而无需重新加载页面本身。
回答by David Constantine
It is kind of nasty solution to your problem... But this can work: You work with those -
这是对您的问题的一种讨厌的解决方案......但这可以工作:您与那些一起工作 -
ob_start();
//printing done here...
ob_end_flush();
at the beginning you will create your rotating ajax gif... Then you do all the processing and calculating you want... At the end of the processing, just echo a small script that does a hide to your gif...
一开始你将创建你的旋转 ajax gif...然后你做所有你想要的处理和计算......在处理结束时,只需回显一个小脚本来隐藏你的 gif ......
Depends on the exact need, maybe ajax can be more elegant solution.
取决于确切的需要,也许 ajax 可以是更优雅的解决方案。
回答by Adam
In response to your conversation with David Constantine below, did you try using ob_flush()?
针对您在下面与 David Constantine 的对话,您是否尝试使用 ob_flush()?
ob_start();
echo '<img src="pics/loading.gif">';
ob_flush();
// Do your processing here
ob_end_flush();
回答by pyramids
I think you don't have a problem with flushing your PHP output to the browser, but more likely with getting the browser to start rendering the partial html output. Unfortunately, browser behavior on partial html is browser-specific, so if you want something to work the same in any browser, the AJAX solution suggested in other answers is the better way to go.
我认为您将 PHP 输出刷新到浏览器没有问题,但更有可能让浏览器开始呈现部分 html 输出。不幸的是,部分 html 上的浏览器行为是特定于浏览器的,因此如果您希望某些内容在任何浏览器中都相同,那么其他答案中建议的 AJAX 解决方案是更好的方法。
But if you don't like that added complexity of a full AJAX solution, you can try to make your html output "nice" in the sense of providing some body output that can be formatted without needing the rest of the html output. This is were your sample code fails: It spends most of its time outputting data into a script tag inside the html header. The browser never even sees the start of the body until your PHP code has practically finished executing. If you first write your complete body, then add the script tag for the data there, you give the browser something to at least try to render whilst waiting for the final script to be completed.
但是,如果您不喜欢完整的 AJAX 解决方案增加的复杂性,您可以尝试使您的 html 输出“漂亮”,即提供一些可以在不需要其余 html 输出的情况下进行格式化的正文输出。这是您的示例代码失败的原因:它花费大部分时间将数据输出到 html 标头内的脚本标记中。浏览器甚至不会看到正文的开始,直到您的 PHP 代码几乎执行完毕。如果您首先编写完整的正文,然后在那里为数据添加脚本标记,那么您至少可以在等待最终脚本完成的同时尝试渲染浏览器。
I've found the same issue (albeit not in PHP) discussed here: Stack Overflow question "When do browsers start to render partially transmitted HTML?"In particular, the accepted answer there provides a fairly minimal non-AJAX example to display and hide a placeholder whilst the html file hasn't completely loaded yet.
我发现这里讨论了同样的问题(尽管不是在 PHP 中):Stack Overflow question "When do browsers start to render partial transmission HTML?" 特别是,那里接受的答案提供了一个相当小的非 AJAX 示例来显示和隐藏占位符,而 html 文件尚未完全加载。
回答by syfantid
I know this is an old question, but the answer provided in this pageby rpnew is extremely clear and easy to adjust to your project's requirements. It is a combination of AJAX and PHP.
我知道这是一个老问题,但是rpnew在此页面中提供的答案非常清晰,并且很容易根据您的项目要求进行调整。它是 AJAX 和 PHP 的组合。
The HTML page PHPAjax.html
which calls the PHP script:
PHPAjax.html
调用 PHP 脚本的 HTML 页面:
<html>
<head>
<script type="text/javascript">
document.write('<div id="loading">Loading...</div>');
//Ajax Function
function getHTTPObject()
{
var xmlhttp;
if (window.ActiveXObject)
{
try
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E)
{
xmlhttp = false;
}
}
}
else
{
xmlhttp = false;
}
if (window.XMLHttpRequest)
{
try
{
xmlhttp = new XMLHttpRequest();
}
catch (e)
{
xmlhttp = false;
}
}
return xmlhttp;
}
//HTTP Objects..
var http = getHTTPObject();
//Function which we are calling...
function AjaxFunction()
{
url='PHPScript.php';
http.open("GET",url, true);
http.onreadystatechange = function()
{
if (http.readyState == 4)
{
//Change the text when result comes.....
document.getElementById("content").innerHTML="http. responseText";
}
}
http.send(null);
}
</script>
</head>
<body onload="AjaxFunction()">
</body>
</html>
The Background PHP Script PHPScript.php
:
后台 PHP 脚本PHPScript.php
:
<?php
sleep(10);
echo "I'm from PHP Script";
?>
Save both files in the same directory. From your browser open the HTML file. It will show 'Loading...' for 10 seconds and then you will see the message changing to "I'm from PHP Script".
将两个文件保存在同一目录中。从浏览器打开 HTML 文件。它将显示“正在加载...” 10 秒钟,然后您将看到消息更改为“我来自 PHP 脚本”。