用ajax睡觉

时间:2015-01-08 08:37:58

标签: php ajax

我有一个index.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上运行它的工作,因为它可以显示文本,用户将看到&#39;在屏幕上,无需等待20秒。但如果我用ajax调用它,如下所示:

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

它无法显示用户将看到的文字&#39;为了我。在等了20秒之后才开始工作。 我该如何解决它们?谢谢

1 个答案:

答案 0 :(得分:0)

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

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