提前關閉連接我正在嘗試執行一個Ajax調用(通過JQuery),該調用將啟動一個相當長的進程。我希望腳本只發送一個指示進程已經啟動的響應,但是JQuery在PHP腳本運行完成之前不會返回響應。我嘗試過使用“關閉”標題(下面),也使用了輸出緩沖;兩者似乎都不起作用。有猜測嗎?或者這是我在JQuery中需要做的事情嗎?<?php
echo( "We'll email you as soon as this is done." );header( "Connection: Close" );
// do some stuff that will take a whilemail( '[email protected]', "okay I'm done", 'Yup, all done.' );?>
3 回答

拉莫斯之舞
TA貢獻1820條經驗 獲得超10個贊
關閉用戶瀏覽器連接,同時保持php腳本運行一直是自[PHP]4.1以來的一個問題。 register_shutdown_function()
被修改,使其不會自動關閉用戶連接。
STS在郵件中發布了最初的解決方案: <?php header("Connection: close");ob_start();phpinfo();$size = ob_get_length();header("Content-Length: $size");ob_end_flush(); flush();sleep(13);error_log("do something in the background");?>
它可以正常工作直到你替換掉 phpinfo()
為 echo('text I want user to see');
在這種情況下,頭永遠不會被發送!
解決方案是在發送頭信息之前顯式關閉輸出緩沖區并清除緩沖區。例子: <?php ob_end_clean();header("Connection: close");ignore_user_abort(true); // just to be safeob_start();echo('Text the user will see'); $size = ob_get_length();header("Content-Length: $size");ob_end_flush(); // Strange behaviour, will not workflush(); // Unless both are called !// Do processing here sleep(30);echo('Text user will never see');?>
我只是花了3個小時試圖弄清楚這個問題,希望它能幫到某人:)
測試:
IE 7.5730.11 Mozilla Firefox 1.81

慕桂英3389331
TA貢獻2036條經驗 獲得超8個贊
Connection: closeContent-Length: n (n = size of output in bytes )
// buffer all upcoming outputob_start();echo "We'll email you as soon as this is done.";// get the size of the output$size = ob_get_length(); // send headers to tell the browser to close the connectionheader("Content-Length: $size");header('Connection: close'); // flush all outputob_end_flush();ob_flush();flush(); // if you're using sessions, this prevents subsequent requests // from hanging while the background process executesif (session_id()) session_write_close(); /******** background process starts here ********/
- 3 回答
- 0 關注
- 660 瀏覽
添加回答
舉報
0/150
提交
取消