2012-07-13 35 views
0

如果我有一個文件在接下來的算法test.php的PHP的Ajax:在PHP算法的實時報告

for ($i = 0; $i < 1000; ++$i) 
{ 
    //Operations... 
    ALERT_TO_MAIN_PAGE($i); 
} 

我打電話test.php的與AJAX形成頁面main.html中

如何跟蹤具有實時值的$i的進度?

所以main.html中會顯示這個樣子,非常時期的PHP文件完成一次迭代:

Done 0. 
Done 1. 
Done 2. 
... 

回答

2

您可以嘗試使用HTML5 Server Sent Events將類似消息發送到瀏覽器。

右鍵關閉the website

<?php 
header('Content-Type: text/event-stream'); 
header('Cache-Control: no-cache'); // recommended to prevent caching of event data. 

/** 
* Constructs the SSE data format and flushes that data to the client. 
* 
* @param string $id Timestamp/id of this connection. 
* @param string $msg Line of text that should be transmitted. 
*/ 
function sendMsg($id, $msg) { 
    echo "id: $id" . PHP_EOL; 
    echo "data: $msg" . PHP_EOL; 
    echo PHP_EOL; 
    ob_flush(); 
    flush(); 
} 

$serverTime = time(); 

sendMsg($serverTime, 'server time: ' . date("h:i:s", time())); 
+0

這正是我所期待的!謝謝 – Novak 2012-07-13 13:17:52

+0

@GuyDavid沒問題^ _ ^高興地幫忙:-) – Neal 2012-07-13 13:19:06

1

你不能做這種方式,因爲操作AJAX等待完成PHP方面。

你應該離線運行你的PHP(在後臺)並使用ajax來簡單地詢問狀態(即從會話讀取關於進度的信息)。

+0

唉唉,但你可以^ _^http://stackoverflow.com/a/11471214/561731 – Neal 2012-07-13 13:15:52

+0

它不是跨瀏覽器 - 只有HTML 5的解決方案。 – 2012-07-13 13:20:35

+1

我說在我的回答^ _^ – Neal 2012-07-13 13:20:59