和阿贾克斯一起睡觉


Sleep with ajax

>我有一个索引.php文件,如下所示:

    ob_end_clean();
    header("Connection: close");
    ignore_user_abort(true); // optional
    ob_start();
    for($i=1; $i<100; $i++) {
      echo $i . "."; echo ('Text the user will see'); echo '<br>';
    }
    $size = ob_get_length();
    header("Content-Length: $size");
    ob_end_flush();     // Will not work
    flush(); 
    // At this point, the browser has closed connection to the web server
    // Do processing here
    sleep(20);
    file_put_contents ('test.txt', 'test', FILE_APPEND);

如果我在浏览器 localhost/index 上运行.php它的工作,因为它可以在屏幕上显示"用户将看到的文本",而无需等待 20 秒。但是如果我像下面这样用 ajax 调用它:

$.ajax({
     url: "index.php"
});

它无法为我显示"用户将看到的文本"。等待 20 秒后即可正常工作。我该如何修复它们。谢谢

我刚刚在所有主要浏览器中使用此 jquery 代码尝试了您的代码,并且都工作正常,它们关闭了连接并显示结果:

$.ajax({
      url: "index.php"
}).done(function(data) {
   $('#remote').html(data);
});