douchilian1009 2016-02-01 15:21
浏览 47

回声/打印东西到页面延迟在PHP中

I want to make a page that will show some results after executing some processes. Each process may take 2-10 seconds. So instead of waiting for all the processes to complete, I want to print the result of each once it is completed.

Eg:

<?php

echo "1";

sleep(5); // some process that will execute 5 seconds

echo "2"

sleep(8); // some process that will execute 8 seconds

echo "3"

sleep(5); // some process that will execute 5 seconds

?>

So on opening this PHP file in browsers, "1" prints, after 5 seconds "2" and son on. How can I do that I PHP? One way to do that is to convert these to separate PHP files and load each of then with ajax. But I don't want to split it into different files.

  • 写回答

1条回答 默认 最新

  • doumengyin0491 2016-02-01 15:38
    关注

    use actions to separate the different parts of the script. that way you don't have to break into separate scripts.

    $action = empty($_REQUEST['action']) ? null : $_REQUEST['action'];
    switch($action){
        case 1:
            // do stuff
            break;
        case 2:
            // do stuff
            break;
        case 3:
            // do stuff
            break;
        case 4:
            // do stuff
            break; 
        default:
            echo "you fucked up";   
    }
    

    Then use ajax like

    function doAjax(action){
      if('undefined' == typeof(action)) action = 1;
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
          document.getElementById("results").innerHTML = xhttp.responseText;
          action++;
          if(action<4) doAjax(action);
        }
      };
      xhttp.open("GET", "myPHPScript.php?action="+encodeURIComponent(action), true);
      xhttp.send();
    }
    doAjax();
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大