我有三个脚本: -
//progress.php
<?php
session_start();
echo $_SESSION["progress"];
?>
//long_progress.php
<?php
for($i=1;$i<=10;$i++){
session_start();
$_SESSION["progress"]=$i;
session_write_close();
sleep(1);
}
?>
<!--index.php-->
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
</head>
<script type="text/javascript">
//Start the long running process
$.ajax({
url: 'long_progress.php',
success: function(data) {
}
});
//Start receiving progress
function getProgress(){
$.ajax({
url: 'progress.php',
success: function(data) {
console.log(data)
$("#progress").html(data);
if(data<10){
getProgress();
}
}
});
}
getProgress();
</script>
<div id="progress"></div>
</html>
所以当我在chrome中加载index.php时,我可以看到progress.php的内容实时变化。请求就像它们应该的那样工作。在Firefox中没有任何反应。 打开相应浏览器的控制台就可以了: 在铬中,数字打印为1-10,应该如此。
然而,在Firefox中,只有多个""
。
我的疑问是,为什么差异,当代码没有问题?这个莫名其妙的问题是什么?它是如何解决的。
此外,请不要将此标记为重复,因为这类似于this,因为它已经有答案,所以无法删除。这个问题也是回答这个问题的基础。
Reference - php/ajax to get contents of long running code in real-time
答案 0 :(得分:0)
你应该移动
session_start();
在你的long_process.php循环中。我不明白为什么你重复打开和关闭会话。您应该在脚本开头一次启动会话,并在结束时关闭它。
试一试。
答案 1 :(得分:0)
我尝试使用FF编写脚本并且按预期工作但是我发现问题...您正在尽快发出请求,这可能会导致意外结果,并且随着访问脚本的用户数量的增加会使服务器过载。
我会将此限制为setTimeout
success: function(data) {
console.log(data)
$("#progress").html(data);
if(data<10){
setTimeout(getProgress, 1000);
}
}