我如何刷新彗星的会话?

时间:2011-04-05 14:49:16

标签: php jquery session comet

我希望在我的网页上有一个像彗星一样的iframe,但是当会话更改时,iframe中的信息执行而不是,并且我在...中执行了$_SESSION变量的转储iframe并没有改变。

我的问题是,当客户$_SESSION发生变化时,如何更新彗星iframe中的$_SESSION变量?

非常感谢^ _ ^

使用代码进行更新:

客户端:

<?php
    session_start();
    if(!isset($_SESSION['count'])) $_SESSION['count'] = 0;
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Test Comet</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type='text/javascript' src='../js/jquery.js'></script>
    <script type="text/javascript">
        function test_function(msg){

            $('p').html(msg)

        }

        $('div').click(clickMe);

        function clickMe(event){
            $.ajax({
                url: 'addSess.php'
            })
        }
    </script>
  </head>
  <body>
      <p>This is a test</p>
      <div>click me</div>
    <iframe src="output.php" width="0" height="0" style="display: none;"></iframe>
  </body>
</html>

彗星iframe(output.php):

<?php
session_start();
ob_start();
echo 'hello';
flush_buffers();
while(true){

    echo "<script>window.parent.test_function('".time().' session: '.$_SESSION['count']."');</script>";

    flush_buffers();

    sleep(1);


}

function flush_buffers(){
    ob_end_flush();
    ob_flush();
    flush();
    ob_start();
}
?>

addSess.php:

<?php
session_start();

if(!isset($_SESSION['count'])) $_SESSION['count'] = 0;
$_SESSION['count']++;


echo $_SESSION['count'];
?>
另外我注意到的另一件事就是它冻结浏览器进入我的网站,一旦我关闭客户端,其他一切都加载

1 个答案:

答案 0 :(得分:0)

只要您对$_SESSION进行更改,所有重新加载到var_dump($_SESSION);的iframe都会看到新会话。您是否正确使用session_start()

请更新一些代码,我们会看到我们可以提供帮助。

<强>更新

首先,你的彗星页面需要set_time_limit(0);所以它无限期地运行(连接仍然可以被切断,你需要做一些事情来重启彗星连接)

第二个关闭,输出缓冲可能会给你错误,PHP在这个意义上是不可靠的,因为它,我的本地测试无法使用你的代码。如果我添加该行:

<iframe src="output.php" width="0" height="0" style="display: none;" onload="alert('Iframe Loaded');"></iframe>

我在更新主页的同时收到警报,这意味着刷新缓冲区无法实际刷新缓冲区。当我在这里获得代码时,我会回来。

<强> UPDATE2

叹息。简单...

$('div').click(clickMe);

需要在HTML DOM加载后调用。尝试:

$(function(){
    $('div').click(clickMe);
});

此外,您应该考虑将彗星代码更改为:

<?php
session_start();
ob_implicit_flush(true);
ob_end_flush();
echo 'hello';
while(true){
    echo "<script>window.parent.test_function('".time().' session: '.$_SESSION['count']."');</script>";
    sleep(1);
}
?> 

通过执行ob_implicit_flush,您不需要经常调用flush_buffers。您还需要ob_end_flush来取消输出缓冲。

您还应注意需要session_destroy。否则,您的站点将等待彗星会话关闭,然后才能开始新会话。

session_start()实际工作的方式是,它等待会话变得可用。这意味着您需要使用session_id为您的彗星生成不同的会话或使用文件......或采用其他技术。