将Javascript变量附加到cookie

时间:2011-10-14 08:48:03

标签: php javascript

我一直在挣扎,也许有人可以帮助我吗?我的页面上有一个javascript计数器,试图将它附加到cookie(My first quetion about this),这样如果用户刷新页面,计数器就不会再从0开始:

第1页:

<head>
<script type="text/javascript">
var pageVisisted = new Date(); 
setInterval(function() {
    var timeOnSite = new Date() - pageVisisted;
    var secondsTotal = timeOnSite / 1000;
    var hours = Math.floor(secondsTotal / 3600);
    var minutes = Math.floor(secondsTotal / 60) % 3600;
    var seconds = Math.floor(secondsTotal)  % 60;
    document.getElementById('counter').innerHTML = hours + ":" + minutes + ":" + seconds;
}, 1000);
</script>
<?php
setcookie(AboutVisit, pageVisisted);
session_start();
?>
</head>

第2页:

$cookid = $_COOKIE['AboutVisit'];
echo $cookid;

但是我得到了显示:pageVisisted

1 个答案:

答案 0 :(得分:0)

setcookie(AboutVisit, pageVisisted);不会捕获pageVisited的值,因为这是一个JavaScript变量。 JavaScript在用户的浏览器中运行,而PHP却没有意识到它。 PHP只知道它的PHP块中有什么。换句话说,它会看到你的代码:

Arbitrary text
<?php
setcookie(AboutVisit, pageVisisted); // What is pageVisited?!
session_start();
?>
Arbitrary text

实际上,就跟踪某人在您的网页上的时间而言,您不需要涉及PHP,除非您需要在服务器上使用该信息。相反,您的JavaScript可以负责维护您的Cookie。不幸的是,JavaScript本身有一个可怕的和反直觉的API来处理cookie。由@vascowhite链接的文章有一组很好的帮助JavaScript函数,您可以使用它们来简化操作。以下是添加一些辅助函数后JavaScript的样子:

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

// Read the cookie; if it's not there, start at the current date
var cookieVal = readCookie('AboutVisit');
var pageVisisted = cookieVal ? parseInt(cookieVal) : new Date().milliseconds;
if (!cookieVal) {
    createCookie('AboutVisit', pageVisited.toString());
}

setInterval(function() {
    var timeOnSite = new Date().milliseconds - pageVisisted;
    var secondsTotal = timeOnSite / 1000;
    var hours = Math.floor(secondsTotal / 3600);
    var minutes = Math.floor(secondsTotal / 60) % 3600;
    var seconds = Math.floor(secondsTotal)  % 60;
    document.getElementById('counter').innerHTML = 
        hours + ":" + minutes + ":" + seconds;
}, 1000);