1

我再次向 SO 社区寻求一点帮助。

我正在修改一个 Joomla“测验”组件,使其按照我需要的方式运行。我现在要做的是改变组件的“刷新”行为。基本上,每个测验都有一个超时时间,即用户不再可以访问测验的时间,所以当计时器变为 0 时,测验被提交等等,但是这个组件的默认行为使得每当页面刷新,计时器将重置为初始设置时间(比如 10 分钟)

问题是我希望能够让计时器在刷新的情况下从它离开的地方继续。

自从 3 或 4 年前我就没有使用过 PHP,所以我有点迷路了。

为了能够实现所需的行为,我正在设置一个 cookie,它将存储(通过内爆)初始时间(打开测验时)和“现在”时间(加载时它设置为 0,但刷新时我想要“更新” cookie 以存储重新加载时间)。

通过初始时间和现在时间,我将能够计算已经过去了多少时间并将计时器从它停止的地方放置。

问题是,我正在尝试使用 javascript 'onbeforeunload' 来“更新” cookie,以便我可以设法将刷新时间放入 cookie。但由于某种原因,它根本没有做任何事情。当我去查看 cookie 内容时,一切都与设置 cookie 时一样。

我知道为了更新 cookie,我必须删除它然后重新设置它,但我没有成功。

下面是示例代码:

//This is responsible for setting the cookie (via PHP):
<?php
$name = "progress";
$now = 0;
$time_diff = 0;
$expire = time() + 3600;
$data = array(time(), $now, $time_diff, $this->quiz->time_limit);
//$var = implode(',', $data);

if(isset($_COOKIE[$name])) {
    /* If defined, update the timer */

} else {
    setcookie($name, implode(',',$data), $expire);
}
echo $_COOKIE[$name];
echo "<br />";
echo $this->quiz->time_limit;
?>

这是为了检测“刷新”事件(使用将运行 PHP 的 Javascript):

window.onbeforeunload = function() {
    <?php
        $name = "progress";
        $list = explode($_COOKIE[$name]);
        //delete cookie
        setcookie($name, "", time() - 3600);

        //Update the fields
        $list['1'] = time(); //now - refresh time
        $list['2'] = $list['1'] - $list['0']; //time_diff

        //Set the cookie again
        setcookie($name, implode(',', $list), time() + 3600);
    ?>
}

谁能指出这段代码有什么问题?

4

1 回答 1

2

As has been said in the comments, JavaScript cannot run PHP code like that... but if you use AJAX then you can. Now with the code you posted for us to see, if you load up your page in the browser and view the code your function will look like this:

window.onbeforeunload(){

}

So it's no surprise that nothing is happening with your cookies when you are closing your browser. Now, without seeing your other functions it's hard to tell exactly what is happening but you can use PHP and JavaScript intertwined but in a different fashion. Let me explain this with an example.

window.onbeforeunload(){
  var name = <?php $name='Steve'; echo($name); ?>;
  console.log(name);
}

If you had this code and loaded the page in the browser you would no longer see the PHP code, but instead would see this:

window.onbeforeunload(){
  var name = 'Steve';
  console.log(name);
}


With that being said, here are a few links you might find helpful.

于 2013-03-26T19:13:01.823 回答