Flush problem with ajax
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('loa开发者_C百科ding...');
},
success: function( data ) {
$('#mydiv').html( data );
}
});
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.
I'd say the success handler is not being called because the response body is never entirely finished.
精彩评论