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