我正在尝试实现 php 脚本循环的实时轮询,但到目前为止我的尝试没有运气。到目前为止,这是我所拥有的:
在表单提交时:
$.ajax({
data: $(this).serialize(),
success: showResponse,
url: 'process.php',
type: 'post'
});
function showResponse(){
$.ajax({
type: "GET",
url: "progress.php",
cache: false,
success: function(data) {
var response = $.parseJSON(data);
if (response.processing === true) {
console.log("Current Item: " + response.currentItem +
"Total Items: " + response.totalItems +
"Percent Complete: " + response.percentComplete);
setTimeout(checkProgress, 1000);
});
}
在 process.php 脚本中:
session_start();
echo json_encode(array("processing" => true));
$totalItems = 10000000;
$_SESSION['totalItems'] = $totalItems;
$_SESSION['processing'] = true;
$_SESSION['error'] = false;
for ($i=0; $i <= $totalItems; $i++) {
$_SESSION['currentItem'] = $i;
$_SESSION['percentComplete'] = round(($i / $totalItems * 100));
}
在进度 php 脚本中:
session_start();
echo json_encode(array(
"processing" => $_SESSION['processing'],
"error" => $_SESSION['error'],
"currentItem" => $_SESSION['currentItem'],
"totalItems" => $_SESSION['totalItems'],
"percentComplete" => $_SESSION['percentComplete']
)
);
不知道我在哪里出错了,但它所做的只是在完成 100% 后循环。任何建议将不胜感激!
编辑 我将上面的内容更改为在 process.php 中使用 apc:
apc_store('totalItems', $totalItems);
apc_store('processing', true);
apc_store('error', false);
apc_store('currentItem', $i);
apc_store('percentComplete', round(($i / $totalItems * 100)));
在progress.php中:
echo json_encode(array(
"processing" => apc_fetch('processing'),
"error" => apc_fetch('error'),
"currentItem" => apc_fetch('currentItem'),
"totalItems" => apc_fetch('totalItems'),
"percentComplete" => apc_fetch('percentComplete')
)
);
仍然无法按照我希望的方式正常工作,是我做错了什么吗?它只显示错误值,直到脚本完成并显示 100%,就像之前的会话使用一样。有任何想法吗?