提前关闭连接我正在尝试执行一个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( 'dude@thatplace.com', "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 关注
- 625 浏览
添加回答
举报
0/150
提交
取消