问题
I'm running a PHP script that accesses some MySQL databases, and I need to wait a few seconds until the previous script has entered all the information into the database. The wait time shouldn't be long, but just in case servers are slow on an off day, I'm using sleep(10) to wait 10 seconds before executing the script. I wanted to display a "please wait" message, while it is waiting that 10 seconds, but unfortunately that message gets displayed only after the 10 seconds has already been completed. This is the way I'm going at it:
ob_start();
echo "Please wait while your invoice is being created... </br>";
ob_flush();
sleep(10);
ob_end_clean();
echo "Success...";
Based on some research online, I was under the impression that ob_flush() would output the text before the 10 seconds was up, and then ob_end_clean() would erase the previously printed text, but what I'm getting instead is that both texts are being displayed after the 10 seconds is up and the first text is not being erased. Do you guys know what I'm doing wrong here?
回答1:
You cannot edit anything you have outputted already with PHP, that would require a page reload. ob_flush just outputs the buffer and empties it. ob_end_clean() stops the output buffering, allowing you to output normally again.
To hide shown text you would output a javascript to hide the previously rendered text (preferably wrapped in a div or so for ease of selecting).
来源:https://stackoverflow.com/questions/11995248/php-time-delay-using-ob-flush-with-loading-message