PHP与AJAX-向用户发送响应后继续处理 [英] PHP with AJAX - Continue Processing After Sending Response to the User

查看:51
本文介绍了PHP与AJAX-向用户发送响应后继续处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在服务器端进行很多处理,但是不希望用户意识到这一点.我想立即向用户发送响应,然后在服务器端运行该过程.

我已经做了一些研究,到目前为止,我已经做到了:

 函数process(){ignore_user_abort(true);set_time_limit(0);ob_start();//向用户发送回复header('Connection:close');header('Content-Length:'.ob_get_length());ob_end_flush();ob_flush();flush();//后期过程} 

据我所知,这应该立即返回用户响应,然后运行后期处理.但这不起作用:它仍然等待所有过程完成.

顺便说一句,如果有帮助,我正在发送一个AJAX请求.起初我以为可能是会话锁定有问题,但是现在我什至不使用任何会话( session_status()返回 1 ).

PHP版本是7.1

注意:我已经阅读了其他相关问题,上述方法可以很好地解决上述问题,但是由于某种原因,该方法不适用于我的情况.

解决方案

刷新输出似乎不适用于AJAX(如@ADyson在评论中所述).因此,解决该问题的唯一方法是使用Cron Job.为此,我使用了 PHP Cron Scheduler .但是 crontab 可以直接用于将Cron作业添加到列表中.

我将后进程添加到另一个经过适当更改的PHP文件中,以便它可以执行脚本中的相同任务,并将文件添加到Scheduler中.

这个解决方案似乎很痛苦,但是除了使用Cron Job之外,没有其他解决方案.

I have to do a lot of processing in the server end, but don't want user to aware of it. I want to send user a response immediately and then run the process in the server end.

I've done some study, and so far I've done this:

function process(){
    ignore_user_abort(true);
    set_time_limit(0);

    ob_start();
    // Send response to the user
    header('Connection: close');
    header('Content-Length: '.ob_get_length());
    ob_end_flush();
    ob_flush();
    flush();

    // Post process

}

As far as I'm aware of, this should return the user response immediately and then run the post processes. But it's not working: it still waits until all the processes are done.

Bytheway, I'm sending an AJAX request if it helps. At first I thought it might be a problem with session locking, but now I'm not even using any session (session_status() returns 1).

PHP version is 7.1

NOTE: I've read other related questions where the above method works fine, but for some reason it's not working in my case.

解决方案

It looks like (as @ADyson said in the comment) flushing output doesn't seem work with AJAX. So, the only solution to the problem is to use Cron Job. To do this, I used PHP Cron Scheduler. But crontab can be used directly to add a Cron Job to the list.

I added the post processes to another PHP file with suitable changes so that it can do the same tasks from the script and added the file to the Scheduler.

This solution may seem a real pain, but there is no solution to this problem other than using Cron Job.

这篇关于PHP与AJAX-向用户发送响应后继续处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆