【问题标题】:Redirect Function Based on Cookie基于 Cookie 的重定向功能
【发布时间】:2012-06-11 03:47:57
【问题描述】:
我在我的 js 文件中使用此代码进行重定向
setTimeout('top.location=\'http://google.com/?123\';', 1000);
问题是我的 js 文件执行了很多次,但我想在 js 文件中添加一些 cookie 代码,这样我的访问者就不会一次又一次地重定向。那么除非我手动更改 cookie,否则只执行一次此 js 文件的 cookie 代码将是什么
【问题讨论】:
标签:
php
javascript
cookies
session-cookies
【解决方案1】:
在创建代码时牢记此功能,按顺序使用这些步骤。您可以查看您的 js 参考,了解如何执行这些步骤。我希望这能为您指明正确的方向。
- 检查现有的 cookie。
- 如果找到 cookie,请不要重定向,否则,请重定向。 (这就是您现有的生产线的用武之地。)
- 根据您希望它们重定向的频率设置具有超时值的 cookie。
【解决方案2】:
未测试
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;
}
if(readCookie('redirected')!=true)
{
createCookie('redirected',true,0); // cookie will be trashed after the browser closed.
setTimeout('top.location=\'http://google.com/?123\';', 1000);
}
Read here.