Flush problem with ajax

我的未来我决定 提交于 2020-01-11 03:57:11

问题


I used flush() function in infinite loop in my php page, it echoes a text each second. when i open the page in browser it works! but when i load it via jquery ajax it doesn't response!

php page

    <?php

if (ob_get_level() == 0) ob_start();

for ($i = 0; true/*$i<10*/; $i++){

        echo "<br> Line to show. $i";
        echo str_pad('',4096)."\n";    

        ob_flush();
        flush();
        sleep(1);

}

ob_end_flush();

?>

jquery code

$.ajax({
  url: 'res.php',

  beforeSend: function(  ) {
    $('#mydiv').html('loading...');
  },
  success: function( data ) {

      $('#mydiv').html(  data );

  }
});

回答1:


HTTP-Streaming can not be done simply using $.get

insert <script> tags as following: http://ajaxpatterns.org/archive/HTTP_Streaming.php.

 <?
      while (true) {
    ?>
        <script type="text/javascript">
          $('news').innerHTML = '<?= getLatestNews() ?>';
        </script>
    <?
        flush(); // Ensure the Javascript tag is written out immediately
        sleep(10);
      }
    ?>

HTTP-streaming is a very complicated hack. You should consider using long-polling instead which works in every browser. It seems there are some solutions (slide 54)

Simple long-polling example topic:

How do I implement basic "Long Polling"?

This video shows how to do long-polling: http://www.screenr.com/SNH

P.S: this will kill your(bad performance) server for sure. You should have a look at http://pusherapp.com which is free for small sites.




回答2:


I'd say the success handler is not being called because the response body is never entirely finished.



来源:https://stackoverflow.com/questions/6488493/flush-problem-with-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!