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);
    ?>
  • 相关阅读:
    Linux系统调用
    Linux的中断 & 中断和异常的区别
    system v和posix的共享内存对比 & 共享内存位置
    epoll里面mmap释疑
    提高网络效率的总结
    推荐相关学习 & 典型算法、典型特征、典型推荐系统框架
    最大似然法理解
    调试多线程 & 查死锁的bug & gcore命令 & gdb对多线程的调试 & gcore & pstack & 调试常用命令
    内存屏障 & Memory barrier
    锁相关知识 & mutex怎么实现的 & spinlock怎么用的 & 怎样避免死锁 & 内核同步机制 & 读写锁
  • 原文地址:https://www.cnblogs.com/guoyinglichong/p/7087288.html
Copyright © 2011-2022 走看看