ajax请求aborted,connection_aborted()在ajax调用上不起作用

这篇博客讨论了如何在PHP中确保脚本即使在用户断开连接时也能继续执行。通过使用`ignore_user_abort(true)`和`ob_flush()`,可以实现在浏览器关闭后继续记录日志的功能。示例代码展示了如何在用户关闭浏览器后,脚本依然能检测到连接状态并写入错误信息到日志文件。这对于后台任务和长时间运行的脚本是很有用的。
摘要由CSDN通过智能技术生成

小编典典

您将需要添加“ ignore_user_abort(true);” 在PHP脚本之上,并在从脚本中回显某些内容后调用“

ob_flush()”(有关原因,请参见PHP

flush()手册页 )。工作示例(概念验证):

ignore_user_abort(true);

function log_message($s, $ss) {

$myFile = "log.txt";

$fh = fopen($myFile, 'a') or die("can't open file");

$stringData = $s . ": " . $ss . "\n";

fwrite($fh, $stringData);

fclose($fh);

}

for ($i=0;$i<5;$i++) {

echo "
";

//flush();

ob_flush();

if (connection_aborted()) {

log_message('error1', connection_status());

exit;

}

else {

log_message('error2', connection_status());

}

sleep(1);

}

如果连接仍处于活动状态,则PS connection_status()返回0,如果关闭则返回1。

编辑:

我的错。调用flush()和ob_flush()(请阅读flush()手册页,上面的链接,以及

本主题的),否则可能不起作用,具体取决于服务器/ php配置。以下代码已在WAMP和PHP

5.3.8上进行了测试(无需调用flush()即可工作),现在已在Ubuntu PHP

5.3.10上进行了测试。需要在ob_flush()之前调用flush()的位置。

完整的测试代码:

index.html:

$(document).ready(function() {

$.ajax({

url: "script.php",

context: document.body

}).done(function(data) {

alert(data);

});

})

script.php:

ignore_user_abort(true);

function log_message($type, $message, $file = 'log.txt') {

$fh = fopen($file, 'a') or die("can't open file");

$conn_status = connection_status();

if($conn_status === CONNECTION_NORMAL) {

$status = 'normal';

} elseif($conn_status === CONNECTION_ABORTED) {

$status = 'aborted';

} else {

$status = 'timeout';

}

$aborted = connection_aborted() ? 'yes' : 'no';

$data = $type . ': ' . $message . "\n";

$data .= 'Connection status: ' . $status . "\n";

$data .= 'Aborted: ' . $aborted . "\n\n\n";

fwrite($fh, $data);

fclose($fh);

}

for ($i = 0; $i < 10; $i++) {

echo "
";

flush();

ob_flush();

if (connection_aborted()) {

log_message('Error', 'Connection closed by user!');

exit;

}

else {

log_message('Info', 'Everything is fine. Move along...');

}

sleep(1);

}

调用index.html页面并关闭选项卡或整个浏览器后,您应该在log.txt文件中看到以下信息:

Info: Everything is fine. Move along...

Connection status: normal

Aborted: no

Info: Everything is fine. Move along...

Connection status: normal

Aborted: no

Info: Everything is fine. Move along...

Connection status: normal

Aborted: no

Error: Connection closed by user!

Connection status: aborted

Aborted: yes

2020-07-26

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值