[英]Can a php script called using Ajax post send back SSE events while the script executes
我的服務器上有一個 php 腳本,它執行多項任務(設置文件夾、復制文件等),我用 ajax 調用該腳本。
IE
注冊.js:
const evtSource = new EventSource("/createuser.php", { withCredentials: true } );
evtSource.onmessage = function(event) {
console.log(event.data);
}
$.ajax({
type: 'POST',
url: '/createuser.php',
dataType: 'json',
data: {
'username': "test user",
'usertype' : "author"
},
success: function(data){
console.log("user created");
}
});
現在在 createuser.php 上,我嘗試向我的網頁發送一條消息:
創建用戶.php:
<?php
function SendProgressMessage($op){
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
switch($op){
case "userCreated":
echo "User Created";
break;
case "foldersCreated":
echo "Folder structure created";
break;
case "TemplatesCopied":
echo "Templates Copied";
break;
}
flush();
}
?>
我可以將 evtSource 設置為相同的腳本和 ajax 調用還是為腳本創建 2 個會話?
你不能這樣設置,AJAX 請求會在服務器端產生一個新的 PHP 進程,它不知道第一個進程。
長時間工作的腳本應該將狀態存儲到數據庫中,從那里可以通過第二個(,第三個,...)請求獨立查詢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.