是否有一种方法可以在未完成的情况下从PHP过程中获取更新,并且AJAX已将其调用?通过更新,我的意思是从php脚本中冲洗输出。
var proc;
$('#start').click(function () {
proc = $.ajax({
type: 'POST',
url: 'execute.php',
// getData function that will get me updated data
getData: function (update){
alert(update);
}
});
});
更新:可以说我们想在此之前获得回声。
execute.php
<?php
$progress = 0;
while(1){
$progress++;
echo $progress;
flush();
sleep(5);
if($progress == 100){
break;
}
}
?>
最终:
myScript.js
var strongcalcs;
var source;
$('#start').click(function () {
strongcalcs = $.ajax({
type: 'POST',
url: 'execute.php',
beforeSend: function () {
rpm_percent();
},
success: function(result){
source.close();
},
complete: function () {
source.close();
},
error: function () {
source.close();
}
});
});
function rpm_percent() {
source = new EventSource("execute.php");
if(typeof(EventSource) !== "undefined") {
source.onmessage = function(event) {
console.log(event.data);
};
} else {
alert("nono");
}
}
execute.php
<?php
$coco = 0;
function sendMsg($msg, &$coco) {
echo "id: " . $coco . "n";
echo "data: " . $msg;
echo "n";
echo "n";
ob_flush();
flush();
$coco++;
}
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
$progress = 0;
while(1){
sendMsg($progress++, $coco);
ob_flush();
flush();
sleep(5);
if($progress == 100){
break;
}
}
?>
我过去曾经用过的服务器已发送事件(https://www.w3schools.com/html/html/html5_serversentevents.asp(。开箱即用的Internet Explorer不受支持,但是可以解决问题。
我认为Websockets做类似的事情,但我自己没有经验。
您可以在服务器上成功加载文件时使用AJAX回调。
$('#start').click(function () {
proc = $.ajax({
type: 'POST',
url: 'execute.php',
success: function (respon){
//do what u want to do here.
if(respon.status == 0){
alert("failed");
}
else{
alert("ok");
}
},
error: function(xhr, error){
//for error handling
}
});
});
,在您的php中,您可以回应您要显示的内容
<?php
$var["status"] = 0;
//if(your condition){ $var["status"] = 1;}
return json_encode($var);
?>
有关您可以在此处和此处看到的更多信息