Get results from php script via jquery load() function before php script finishes
I have the following situation:
jquery:
$(function(){
$('input[type="button"]').click(function(){
$('#result').load('script.php');
});
});
script.php:
<?php
echo "1";
sleep(2);
echo "2";
sleep(2);
echo "3";
?>
Currently the jquery load function will wait for the php script to finish and then display the result into the targeted div...so in this case it will wait 4 seconds and then display 123.
What I'm trying to achieve is to ha开发者_如何学编程ve the jquery load function to return the results separately, live, before the php script finishes. By separately I mean to see in the targeted div 1 then wait for 2 seconds, then see 2, then another 2 seconds and then 3.
Is this possible with my example?
bad idea to temporize on the server side, you should do it on the client with setTimeout function(s) : get instant response from the server, and use it however you like on the client :
$.get('script.php', function(data){
$('#div1').yourcode();
setTimeout(function(){
$('#div2').yourcode();
}, 2000);
});
No. Out of the box, this will not be possible with jQuery.load(). The two previous answers are right on -- you'll either need to rework XMLHttpRequest which would be a horribly complex project, or you'll have to poll your server using Javascript (setTimeout) and get discrete values from the server to display on the client side. Without knowing more about exactly what you're trying to do, I would suggest using the latter approach (polling) as suggested by darma.
I don't think you would be able to do it with jquery because, as far as I know, any callback/handler functions you pass will not run until after the XMLHttpRequest
has finished (or reached ready state 4 meaning request done). You might be able to use flush() in php to send the output after an echo and then use your own ajax XMLHttpRequest
object/script and look for another ready state such as 3 which should contain partial request data. It is a PITA to do though mostly because of browser inconsistencies with ready states and I haven't seen a pre-made library that can do this so you would probably have to write something yourself.
Some info about using ready states
精彩评论