发送 AJAX 结果但在 PHP 中继续处理

2022-01-24 00:00:00 connection php javascript ajax

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.

相关文章