zoukankan      html  css  js  c++  java
  • php提前输出响应及注意问题

    1、浏览器和服务器之间是通过HTTP进行通信的,浏览器发送请求给服务器,服务器处理完请求后,发送响应结果给浏览器,浏览器展示给用户。如果服务器处理请求时间比较长,那么浏览器就需要等待服务器的处理结果。

    但是,有时候,浏览器不需要等待服务器的处理结果,只要发送的请求已经被服务器接收到。所以,这种情况下,浏览器希望服务器接收到请求立即返回一个响应,比如字符串'success'。这样浏览器可以继续执行后续代码。

      解决方法,

      使用的服务器是nginx+fpm

       echo 'success';

       fastcgi_finish_request();

      //执行耗时代码

       如果服务器使用的是apache、ob_end_flush();

    ob_start();
    echo 'success';
    
    header("Content-Type: text/html;charset=utf-8");
    header("Connection: close");
    header('Content-Length: '. ob_get_length());
    
    ob_flush();
    flush();
    //执行耗时代码

    2、测试
    1》test.html
    <!DOCTYPE html>
    <html>
    <head>
      <title>郭颖的测试</title>
      <meta charset="utf8">
    </head>
    
    <body>
    </body>
    <script src="jquery-3.0.0.js"></script>
    <script>
    function getCurTime(d) {
      var time = d.getFullYear() + "-" +(d.getMonth()+1) + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
      return time;
    }
    
    function getOther(url) {
      $.ajax({
        url: url,
        success:function(data){
          console.log(data);
          console.log(getCurTime(new Date()));
        }
      });
    }
    
    console.log(getCurTime(new Date()));
    $.ajax({
      url: "http://localhost/test.php",
      success:function(data){
        console.log(data);
        console.log(getCurTime(new Date()));
        getOther("http://localhost/test2.php");
      }
    });
    
    </script>
    </html>

    2> test.php

    <?php
    echo 'success';
    //使用sleep函数模拟耗时任务,耗时5秒
    sleep(5);
    ?>

    3>test2.php

    <?php
    echo 'this is test2.php';
    ?>

    运行localhost/test.html

    在控制台输出

    由此可以看出

     浏览器需要等待test.php文件执行完才能去请求test2.php文件。

    接下来修改test.php文件内容,提前输出响应

    <?php
    if(!function_exists('fastcgi_finish_request')) {
      ob_end_flush();
      ob_start();
    }
    echo 'success';
    
    if(!function_exists('fastcgi_finish_request')) {
      header("Content-Type: text/html;charset=utf-8");
      header("Connection: close");
      header('Content-Length: '. ob_get_length());
      ob_flush();
      flush();
    } else {
      fastcgi_finish_request();
    }
    
    sleep(5);
    ?>
  • 相关阅读:
    安装cloudbase-init和qga批处理
    Windows添加自定义服务、批处理文件开机自启动方法
    Windows批处理:自动部署常用软件(静默安装)
    windows auto activate
    XML转译字符
    Leetcode908.Smallest Range I最小差值1
    Leetcode917.Reverse Only Letters仅仅反转字母
    Leetcode896.Monotonic Array单调数列
    Leetcode905.Sort Array By Parity按奇偶排序数组
    Leetcode892.Surface Area of 3D Shapes三维形体的表面积
  • 原文地址:https://www.cnblogs.com/guoyinglichong/p/7087288.html
Copyright © 2011-2022 走看看