【问题标题】:PHP output buffering Loop and Jquery AjaxPHP 输出缓冲循环和 Jquery Ajax
【发布时间】:2012-04-26 06:12:06
【问题描述】:

我阅读了很多关于彗星编程的文章,但我正在考虑这种实现是否可行。

这是我的脚本

$.ajax({
   url:"mypage.php",
   onProgress:{function(rsp){ //i know there is no such function like this
     $("#mydiv").append(rsp+"<br>");
   }}
});

这是我的 mypage.php

<?php
    while(true){
    ob_start();
      echo time();
    ob_flush();
    }
    ?>

现在我想要的是我的 ajax 请求会在进程中获取结果。这可能吗?

【问题讨论】:

标签: php jquery ajax comet infinite-loop


【解决方案1】:

要让这件事发生,你必须使用彗星技术.... 请参考

What is the best way of showing progress on an Ajax call?

【讨论】:

    【解决方案2】:

    如果您只想抓紧时间,这就是轮询方式。为什么要无限循环使用资源。

    <?php
    //polling.php
    if(isset($_GET['poll']) && $_GET['poll']=='1'){
    $out = array('thetime'=>date("F j, Y, g:i:s a")); 
    echo json_encode($out);
    die;
    }
    ?>
    
    
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>
    function poll(){
       setTimeout(function(){
    
          $.ajax({ url: "http://localhost/polling.php?poll=1",cache: false,
          success: function(data){
          //Do something with returned json
          $("#time").replaceWith("<p id=\"time\">The Server Time & Date is: "+ data.thetime +"</p>");
            //Next poll
            poll();
          }, dataType: "json"});
         // 1/2 a sec
      }, 500);
    }
    
    $(document).ready(function(){
        poll();
    });
    </script>
    
    <p id="time">The Server Time & Date is: <?php echo date("F j, Y, g:i:s a");?></p>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多