开发者

AJAX request PHP-script loop

I have looked around for similar topics but none seem to address the problem I am currently having. I have this JavaScript:

<script type="text/javascript">

                http = new XMLHttpRequest();

                function fetch()
                {

                    http.open("GET", "script.php", true);
          开发者_运维技巧          http.onreadystatechange = useHttpResponse;
                    http.send(null);

                }

                function useHttpResponse()
                {

                    if(http.readyState == 4)
                    {

                            var textout = http.responseText;
                            document.getElementById("ajax").innerHTML=textout;

                    }

                }

</script>

Extremely basic stuff. PHP-script is a simple loop:

for($i = 0; $i < 30000; $i++)
{

      echo 'Hello<br />';

}

This works great. I press a button that has onClick="javascript:fetch()" and it requests the PHP-script and outputs 30.000 lines of "Hello" in the div with id "ajax".

The problem is that it has to wait until it has run all 30.000 loops. I want it to output the response via the AJAX request after EACH loop so that the list kind of expands as the script is running. Is this possible? How would I do this? Like I said, I have searched but come up empty. I realize this is strictly a cosmetic effect but I would be greatful for any advices!

Thank you


disable output buffering in your PHP settings or call http://www.php.net/manual/en/function.flush.php after each iteration.

As pointed out by Mike. in your XHR's onreadystatechange, you're checking for status == 4, which means all the data has been transferred. You should check for status == 3, which means The request is in process; often some partial data is available from the response, but the server isn't finished with its response.

Mike also pointed out that if your server is set to use compression, then all output must not be buffered and you cannot stream your HTML content.


No, it's not possible. You cannot fetch data while the script is running, even if some output has been sent. AJAX can only read the complete result.

See the question I asked on this subject: Long Polling/HTTP Streaming General Questions

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜