发送 AJAX 结果但在 PHP 中继续处理 [英] Send AJAX results but continue processing in PHP

查看:25
本文介绍了发送 AJAX 结果但在 PHP 中继续处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I'm using AJAX to update some values in a database. All has worked wonderfully with that, but now I would like to implement some logging stuff. The logging functions look like they are going to take a fair amount of processing time, and theirs no reason that the user should have to wait for them to finish to see their AJAX results.

So, I'm trying to find a way to send AJAX results and still continue processing on the server side. My research has brought up the ignore_user_abort function, but apparently I'm not using it correctly.

This guide is what I'm basing my code off.

Here's my javascript (Jquery) :

 $.ajax({
            type: "GET",
            url: "ajax.php",
            data: { "mydata": mydata },
            success: function(msg) {
                    $("span#status").fadeOut(200, function() {
                            $("span#status").html(msg);
                            $("span#status").fadeIn(200);
                    });

            }
    });

And my PHP:

    $response = "This is my response";

    //Begin code from link
    ob_end_clean();
    header("Connection: close");
    ignore_user_abort(true);
    ob_start();
    echo $response;
    header("Content-Length: " . mb_strlen($response));
    ob_end_flush();
    flush();
    //End code from link

    echo "I should not see this text";

Unfortunately, I am seeing that text after the flush();

Any ideas?

Update - Fixed: I figured out my error. After copying word for word tons of different code suggestions, I figured it must have been an error in my apache/php configuration. Turns out I need to add two lines to force apache not to buffer my results:

apache_setenv('no-gzip', 1);
ini_set('zlib.output_compression', 0);

解决方案

The PHP script cannot tell the browser to close the connection and not wait for further data. Using flush(); only sends the current output down the chain, to the web server, but it does not guarantee it will arrive to the browser immediately. The web server may cache the output until the PHP script completes the execution.

As the OP wrote in the last paragraph, the solution is to configure Apache to not buffer the results.

这篇关于发送 AJAX 结果但在 PHP 中继续处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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