duansha8115
2014-09-23 16:53
浏览 94

根据php文件的输出动态加载html

I am trying to load php file's output in html div. And I have tried it with jQuery's ($('div').load(url_here)) method and it's working fine, but my php file is as below:

<?php
for( $i = 0 ; $i < 10 ; $i++ )
{
    echo date('h:i:s').'<br>';
    //flush the output buffer
    flush();
    //send the output buffer
    ob_flush();
   //sleep here
    sleep(1);
} ?>

Now this php file prints a single line every second, but when I load this php in html's div, it takes 10 seconds once the page is loaded and then adds 10 lines all together. I want to load div as php file returns a single line every second. I mean, I want html to respond same as php (i.e. load one line every second, so at 1st second it should load 1st line, at 2nd second it should add 2nd line and so on). So, is it possible? (P.S - I am beginner for this dynamic web)

图片转代码服务由CSDN问答提供 功能建议

我正在尝试在html div中加载php文件的输出。 我用jQuery的($('div')。load(url_here))方法尝试了它,它工作正常,但我的php文件如下: < pre> &lt;?php for($ i = 0; $ i&lt; 10; $ i ++) { echo date('h:i:s')。'&lt; br&gt;'; //刷新输出缓冲区 flush(); //发送输出缓冲区 ob_flush(); //在此睡眠 sleep(1); }?&gt; < / code>

现在这个php文件每秒打印一行,但是当我在html的div中加载这个php时,一旦加载页面需要10秒,然后再添加10行 一起。 我想加载div,因为php文件每秒返回一行。 我的意思是,我希望html与php一样响应(即每秒加载一行,所以在第1秒它应该加载第1行,在第2秒它应该添加第2行,依此类推)。 那么,有可能吗? (P.S - 我是这个动态网络的初学者)

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doutun1875 2014-09-23 16:58
    已采纳

    PHP

       <?php
    
            echo date('h:i:s').'<br>';
    
        ?>
    

    And JS

    <script>
    
    var timer_php = setInterval(function(){
    $("#anydiv").load("abovefile.php");
    },1000);
    
    setTimeout(function(){
    clearTimer(timer_php);
    },10000);
    </script>
    
    打赏 评论
  • doudu7626 2014-09-23 16:57

    In order to get the result in every minute, you have to open an ajax request every minute to control the time in javascript, not in php.

    Try:

    var timer = window.setInterval(function()
    {
        $('div').load(url_here); 
    }, 1000);
    

    And remove the for loop and the sleep() in php.

    UPDATE:

    To keep the history of the results, try this out:

    var content = $('div').text();
    $('div').load(url_here).append(content);
    
    打赏 评论

相关推荐 更多相似问题