在 Yii2 中向用户发送 AJAX 响应后如何继续执行脚本?
How to continue a script after AJAX response is sent to user in Yii2?
收到 AJAX 请求后,我想在 PHP 脚本完成之前向用户反馈,因为它需要很长时间。
我认为 yii\web\Response
对象的 send()
方法就是为此而创建的,所以我在控制器操作中尝试了以下操作:
Yii::$app->response->format = Response::FORMAT_JSON;
Yii::$app->response->data = [ 'success' => $someData ];
Yii::$app->response->send();
// code that takes long
sleep(5);
响应已发送,但在休眠 5 秒后。
同样幸运的是:
ob_start();
echo json_encode([ 'success' => $someData ]);
header('Connection: close');
header('Content-Type: application/json');
header('Content-Length: '.ob_get_length());
ob_end_flush();
flush();
// code that takes long
sleep(5);
我对在控制器操作中运行的最后一个代码没有任何信心,但我在第一个代码中就有了它......我错过了什么?
编辑:我正在使用 nginx + PHP_FPM
我想你搜索的是 long polling
这是在 PHP+jQuery
上实现长轮询的很好的工作示例
https://github.com/panique/php-long-polling
这里是相关主题,深入解释了该领域的不同技术(包括长轮询)-- What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?
也可以看看这个视频教程
PHP_FPM 有 fastcgi-finish-request()
可用:
This function flushes all response data to the client and finishes the
request. This allows for time consuming tasks to be performed without
leaving the connection to the client open.
Yii::$app->response->format = Response::FORMAT_JSON;
Yii::$app->response->data = [ 'success' => $someData ];
Yii::$app->response->send();
fastcgi-finish-request();
// code that takes long
sleep(5);
收到 AJAX 请求后,我想在 PHP 脚本完成之前向用户反馈,因为它需要很长时间。
我认为 yii\web\Response
对象的 send()
方法就是为此而创建的,所以我在控制器操作中尝试了以下操作:
Yii::$app->response->format = Response::FORMAT_JSON;
Yii::$app->response->data = [ 'success' => $someData ];
Yii::$app->response->send();
// code that takes long
sleep(5);
响应已发送,但在休眠 5 秒后。
同样幸运的是:
ob_start();
echo json_encode([ 'success' => $someData ]);
header('Connection: close');
header('Content-Type: application/json');
header('Content-Length: '.ob_get_length());
ob_end_flush();
flush();
// code that takes long
sleep(5);
我对在控制器操作中运行的最后一个代码没有任何信心,但我在第一个代码中就有了它......我错过了什么?
编辑:我正在使用 nginx + PHP_FPM
我想你搜索的是 long polling
这是在 PHP+jQuery
上实现长轮询的很好的工作示例https://github.com/panique/php-long-polling
这里是相关主题,深入解释了该领域的不同技术(包括长轮询)-- What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?
也可以看看这个视频教程
PHP_FPM 有 fastcgi-finish-request()
可用:
This function flushes all response data to the client and finishes the request. This allows for time consuming tasks to be performed without leaving the connection to the client open.
Yii::$app->response->format = Response::FORMAT_JSON;
Yii::$app->response->data = [ 'success' => $someData ];
Yii::$app->response->send();
fastcgi-finish-request();
// code that takes long
sleep(5);