我正在使用长轮询通过使用txt文件作为缓冲区来获取进程的状态。我正在通过AJAX启动一个进程并等待该调用的响应,我也开始通过另一个AJAX调用来检查该进程。
时间表如下所示:
Calls | Process Length (time)
=============|============================================================
Main AJAX | |--------------------------------------------------------|
Sub check #1 | |-------|
Sub check #2 | |--------|
Sub check #3 | |---------|
..... |
Sub check #n | |------|
我提供的代码用于子检查。
像这样:
服务器侧
<?php
append_to_txt_json("status", "started operation");
do_operation_1();
append_to_txt_json("status", "op#1 finished");
do_operation_2();
append_to_txt_json("status", "op#2 finished");
do_operation_last();
append_to_txt_json("status", "success");
function do_operation_1(){
do_unimportant_1();
append_to_txt_json("sub1_result", do_sub(1));
do_unimportant_2();
}
function append_to_txt_json($key, $str){
$file_path = "ajax_result.txt";
$data = file_get_contents($file_path);
if(!empty($data)){
$contents = json_decode($data);
if(empty($contents)){
$contents = (object)[];
}
}else{
$contents = (object)[];
}
if(property_exists($contents, $key)){
if(!is_array($contents->{$key})){
$temp = $contents->{$key};
$contents->{$key} = [$temp, $str];
}else{
$contents->{$key}[] = $str;
}
}else{
$contents->{$key} = $str;
}
file_put_contents($file_path, json_encode($contents), LOCK_SH);
}
?>
客户端
<script type="text/javascript">
var finishPolling = false;
var poll = function() {
if (finishPolling === true) {
return;
}
$.ajax({
url: "ajax_result.txt?tz=" + (+new Date()),
dataType: "json",
success: function(data) {
// do some parsing, formatting etc
if ((data.status instanceof Array && data.status[data.status.length - 1] === 'success') || (data.status == 'success')) {
finishPolling = true;
}
},
error: function(err) {
console.log(err);
//finishPolling = true;
},
complete: function() {
if(finishPolling === false){
setTimeout(function() {
poll();
}, 2000);
}
},
timeout: 4000
});
};
</script>
但有时,客户端会尝试访问 - 尚未完全编写的文件 - 并从该文件中获取一半无效的JSON响应。这会导致客户端ajax调用出错,执行.error()
方法。
我如何克服这种情况?
还有其他方法吗?