Java Reference
In-Depth Information
}
setCookie(“pageViewCount”,pageViewCount,”“,”“)
</script>
</head>
<body>
<script>
var pageHTML = “You've visited this page “ + pageViewCount;
pageHTML = pageHTML + “ times since “ + pageFirstVisited;
document.write(pageHTML);
</script>
</body>
</html>
Save this as ch11_q1.htm .
You looked at the cookie functions in Chapter 11, so let's turn straight to the new code.
The fi rst two lines get two cookies and store them in variables. The fi rst cookie holds the number of vis-
its, the second the date the page was fi rst visited.
var pageViewCount = getCookieValue(“pageViewCount”);
var pageFirstVisited = getCookieValue(“pageFirstVisited”);
If the pageViewCount cookie does not exist, it's either because the cookie expired (remember you are
counting visits in the last month) or because the user has never visited the site before. Either way you
need to set the pageViewCount to 1 and store the date the page was fi rst visited plus one month in the
pageFirstVisited variable. You'll need this value later when you want to set the expires value for
the pageViewCount cookie you'll create because there is no way of using code to fi nd out an existing
cookie's expiration date.
if (pageViewCount == null)
{
pageViewCount = 1;
pageFirstVisited = new Date();
pageFirstVisited.setMonth(pageFirstVisited.getMonth() + 1)
pageFirstVisited = pageFirstVisited.toGMTString();
setCookie(“pageFirstVisited”,pageFirstVisited,”“,”“)
}
In the else statement, increase the value of pageViewCount .
else
{
pageViewCount = Math.floor(pageViewCount) + 1;
}
You then set the cookie keeping track of the number of page visits by the user.
setCookie(“pageViewCount”,pageViewCount,”“,”“)
Search WWH ::




Custom Search