
使用js检测Cookie的话,可以让js执行定时任务,定期检测,我给你写段代码
方法一://使用jquery的cookie方法,之前必须引入jquerycookiejs文件,在网上可以下载到//每隔1秒,执行cookie检测函数
setTimeout("checkCookie()",1000);
//检测cookie函数,如果cookie为空则跳转到登陆页
function checkCookie() {
if($cookie("qqlogin") == "" || $cookie("qqlogin") == null) {
windowlocationhref = "loginhtml";
}
}
方法二:使用js获取cookie
//定义一个函数,用来读取特定的cookie值
function getCookie(cookie_name) {
var allcookies = documentcookie;
var cookie_pos = allcookiesindexOf(cookie_name); //要获取COOKIE的索引长度
//如果找到了索引,就代表cookie存在,
//反之,就说明不存在。
if (cookie_pos == '') {
windowlocationhref = "loginhtml";
}
}
// 调用函数
//每隔1秒,执行cookie检测函数
setTimeout("getCookie('getCookie')",1000);
注:方法二未经测试。
这篇文章主要介绍了js文件Cookie存取值的使用,需要的朋友可以参考下
代码如下:
/
Cookie工具
使用方法:
//存值
var
value
=
"7天";
toolscookie("day",value,
{expires:7});
//将字符串:"7天"
以
"day"这个key保存到cookie中5天
//取值
var
v
=
toolscookie("day");
//用
"day"
这个key从cookie取出值
/
toolscookie
=
function(name,
value,
options)
{
if
(typeof
value
!=
'undefined')
{
//
name
and
value
given,
set
cookie
options
=
options
||
{};
if
(value
===
null)
{
value
=
'';
optionsexpires
=
-1;
}
var
expires
=
'';
if
(optionsexpires
&&
(typeof
optionsexpires
==
'number'
||
optionsexpirestoGMTString))
{
var
date;
if
(typeof
optionsexpires
==
'number')
{
date
=
new
Date();
datesetTime(dategetTime()
+
(optionsexpires
24
60
60
1000));
}
else
{
date
=
optionsexpires;
}
expires
=
';
expires='
+
datetoGMTString();
//
use
expires
//
attribute,
//
max-age
is
not
//
supported
by
IE
}
var
path
=
optionspath
';
path='
+
optionspath
:
'';
var
domain
=
optionsdomain
';
domain='
+
optionsdomain
:
'';
var
secure
=
optionssecure
';
secure'
:
'';
documentcookie
=
[
name,
'=',
encodeURIComponent(value),
expires,
path,
domain,
secure
]join('');
}
else
{
//
only
name
given,
get
cookie
var
cookieValue
=
null;
if
(documentcookie
&&
documentcookie
!=
'')
{
var
cookies
=
documentcookiesplit(';');
for
(
var
i
=
0;
i
<
cookieslength;
i++)
{
var
cookie
=
jQuerytrim(cookies[i]);
//
Does
this
cookie
string
begin
with
the
name
we
want
if
(cookiesubstring(0,
namelength
+
1)
==
(name
+
'='))
{
cookieValue
=
decodeURIComponent(cookie
substring(namelength
+
1));
break;
}
}
}
return
cookieValue;
}
};
第一种:用原生的documentcookie读取cookie
//读取cookies
function getCookie(name)
{
var arr,reg=new RegExp("(^| )"+name+"=([^;])(;|$)");
if(arr=documentcookiematch(reg))
return unescape(arr[2]);
else
return null;
}
使用示例:
getCookie("name")
第二种是用 jquerycookie js *** 作cookie,读取cookie如下:
$cookie('name')
function getCookie(a){
var b = "";
var c = a + "=";
var d = documentcookie;
if (dlength > 0) {
g = dindexOf(c);
if (g != -1) {
g += clength;
f = dindexOf(";", g);
if (f == -1)
f = dlength;
b = unescape(dsubstring(g, f));
};
};
return b;
},
以上就是关于求一段JS代码实时检测Cookies全部的内容,包括:求一段JS代码实时检测Cookies、js文件Cookie存取值的使用、如何js获取cookie并在html上显示用户名等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)