You will often want to deal with more than one cookie at a time, and Script 10.8 shows you how to read from more than one cookie and display the information. This example shares a fair amount of code with the “Using Cookies as Counters” example.
To handle multiple cookies:
1. | ||
2. | if (lastVisit == 0) { lastVisit = ""; } If the value of lastVisit is zero, then put a null value into lastVisit. We now know the user has never been here before. Script 10.8. Use an array to deal with multiple cookies in a single script.
| |
3. | document.cookie = "pageHit=" + hitCt + ";expires=" + expireDate.toGMTString(); document.cookie = "pageVisit=" + now + ";expires=" + expireDate.toGMTString(); These two lines write the two cookies back to disk with an updated hit number and visit date. | |
4. | var outMsg = "You have visited this page " + hitCt + " times."; if (lastVisit != "") { outMsg += "<br />Your last visit was " + lastVisit; } The outMsg variable stores the outgoing message for our site’s visitor and starts off by being set to tell them how many times they’ve been here. The next lines check if the user has been here before (in code: if lastVisit isn’t null) and if they have, we remind them when. | |
5. | document.getElementById("cookieData").innerHTML = outMsg; And finally, outMsg is displayed on the screen, telling the user what they’ve done before. The result of this script is shown in Figure 10.8. Figure 10.8. The two cookies, written to the screen (along with some other text).
|
52.15.210.12