Expiring a cookie based on page views
I'm no whiz at javascript or anything, actually just using cookies for the first time. I need a cookie that saves an ad value for 3 page views on my site. From what I've seen online it's easy to expire a cookie based on time, but I've seen nothing based on page views.
Basically if the cookie gets set on one page, that value will persist for that user in the next 2 page views. I'm thinking I have to actually store two cookies: a string to store that ad value and an integer to count page views.
Here is some pseudo-pseudo-javascript with imaginary cookie helper methods:
var ad_value = getCookie("ad_value"); // ad_value is used later in page
if(ad_value == null) {
ad_value == ""; // value/cook开发者_如何学编程ie will be saved later
} else {
var page_views = getCookie("page_views");
if(page_views > 3) { // if > 3 page views, don't use ad_value and reset cookies
deleteCookie("ad_value");
deleteCookie("page_views");
ad_value = "";
} else {
saveCookie("page_views", ++page_views);
}
}
If a new ad value should be saved, cookie ad_value
will be set and cookie page_views
is saved as 1.
Does anyone have ideas for improvement? Or am I on the right track? Thanks!
You are pretty much on the right track.
If you are doing page refresh using AJAX only, you could also use JavaScript variables to achieve the task. Other than that, on the client side, your idea is efficient enough.
精彩评论