当PHP已经在运行长脚本时,我正试图从Ajax请求中获取一些数据;
但是当Ajax得到响应时,PHP中的脚本就完成了,我需要在运行其他脚本时获得Ajax响应。
JS
setInterval(function(){
$.post( 'progress.php','',
function(data){
$('.-info-').html(data);
});
},100);
progress.php
session_start();
echo $_SESSION['progress'].'%';
运行.php
session_start();
$i=0;
while($i<99){
$i++;
$_SESSION['progress'] = $i;
//sleep(1);
//flush();
}
当"while"
正在运行时,有什么方法可以响应吗?
running.php:
session_start();
$i=0;
while($i<99){
$i++;
// Store progress in Database
}
progress.php:
session_start();
//read progress from Database
PHP不会在每次更新$_SESSION
时转储保存的会话数据的副本。当任何特定进程正在使用会话文件时,它实际上被PHP锁定了
你需要做:
while($i<99){
session_start(); // start session
$i++;
$_SESSION['progress'] = $i;
session_write_close(); // save session data, release session file lock
sleep(...);
}
换句话说,你的代码永远不会工作,因为你的running
脚本会保持会话打开/锁定,阻止progress
访问它
使用flush()将输出发送到浏览器,并使用onreadystatechange在客户端获取响应
$i=0;
while($i<99){
$i++;
echo $i;
flush();
sleep(1);
}
onreadystatechange将从您的脚本中调用wata的每一部分(http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp)
您应该检查状态3-状态3加载下载;responseText保存部分数据。所以你可以很容易地使用它-你可以在这里查看developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
您可以使用全局var,但最好使用静态或单例类
class counter {
private $_progress=0;
public static function doProgress() {
$i=0;
while($i<99){
$i++;
$this->_progress = $i;
}
}
public static function getProgress() {
return $this->_progress;
}
所以正在进行中。php做
echo Counter::getProgress()
在javascript中,您必须使用mermory中的setinterval()函数在intervaled时间调用process.php脚本