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);
?>

最新文章

  1. 关于VC工程的组成
  2. python json学习之路1-认识json格式数据
  3. 解决visualsvn监听ip 错误的问题
  4. thinkphp 常用
  5. 在PeopleSoft系统中实现打印页面的功能
  6. 前端input选中状态时的蓝框
  7. LoadTest中内存和线程Troubleshooting实战
  8. LaTeX入门教程(二)
  9. Lynis 2.2.0 :面向Linux系统的安全审查和扫描工具
  10. CSS BUG 总结
  11. 分析logfilter+session
  12. memge和saveOrUpdate的区别
  13. 使用idea对spring boot项目打jar和war包[文件]
  14. 一个free异常引发的异常
  15. BugkuCTF 计算器
  16. Mongodb中经常出现的错误(汇总)child process failed, exited with error number
  17. oracle 12c创建可插拔数据库(PDB)及用户
  18. 使用IDEA创建Java Web项目并部署
  19. 分析iOS Crash文件,使用命令符号化iOS Crash文件
  20. linux系统安装redis服务器与php redis扩展

热门文章

  1. 【BZOJ1266】[AHOI2006]上学路线route Floyd+最小割
  2. #1560 : H国的身份证号码II(dp+矩阵快速幂)
  3. sql的reader方法注意事项
  4. Nuxt使用高德地图
  5. Quartz使用总结(转发:http://www.cnblogs.com/drift-ice/p/3817269.html)
  6. gitattributes手册
  7. CSS 中z-index全解析(摘自阿里西西)
  8. range开始节点和结束节点
  9. loadrunner脚本篇——Run-time Settings之ContentCheck
  10. Springboot WebSocket例子