根据页面浏览量使 cookie 过期
我不是 javascript 或任何东西的高手,实际上只是第一次使用 cookie。我需要一个 cookie 来保存我网站上 3 个页面浏览量的广告值。从我在网上看到的情况来看,很容易根据时间使 cookie 过期,但我没有看到任何基于页面浏览量的信息。
基本上,如果在一页上设置 cookie,该值将在接下来的 2 个页面视图中为该用户保留。我想我实际上必须存储两个 cookie:一个用于存储广告值的字符串和一个用于计算页面浏览量的整数。
以下是一些具有虚构 cookie 辅助方法的伪伪 JavaScript:
var ad_value = getCookie("ad_value"); // ad_value is used later in page
if(ad_value == null) {
ad_value == ""; // value/cookie 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);
}
}
如果应保存新的广告值,则将设置 cookie ad_value
并将 cookie page_views
保存为 1。
有人有改进的想法吗?或者我走在正确的轨道上吗?谢谢!
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/cookie 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你几乎走在正确的轨道上。
如果您仅使用 AJAX 进行页面刷新,您还可以使用 JavaScript 变量来完成该任务。除此之外,在客户端,你的想法足够有效。
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.