JavaScript Operation Cookies Detailed
This method of operating cookies I used for a long time, but has not encountered any problems, today in the first page to save the cookie, the second page Gets or the third page to get the function, found the limitations of the method, for example, the first page path is http:// Xxxxx/cyb-car2016/h5officeworker/index, the second page path is Http://xxxxx/cyb-car2016/h5AlertController/index, except that the domain name is the same, There is a different namespace, and cookies are saved on the current page by default, so the cookies are saved on the first page, because the second page will not get the cookies because the paths are saved differently. The workaround is to set the Path,document.cookie = name + "=" + Escape (value) + "expires=" + exp.togmtstring () + ";p ath=/" when saving cookies; , where path=/indicates that it is saved under the domain name path and is available globally
?
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
/***********************操作cookies的方法***************************/
//写cookies
//这是有设定过期时间的使用示例:
//s20是代表20秒
//h是指小时,如12小时则是:h12
//d是天数,30天则:d30
function setCookie(name,value,time){
var strsec = getsec(time);
var exp =
new Date();
exp.setTime(exp.getTime() + strsec*1);
document.cookie = name +
"="
+ escape (value) +
";expires=" + exp.toGMTString()+
";path=/"
;
}
//读取cookies
function getCookie(name){
var arr,reg=
new RegExp(
"(^| )"
+name+
"=([^;]*)(;|$)"
);
if
(arr=document.cookie.match(reg))
return unescape(arr[2]);
else
return false
;
}
// 删除cookies
function delCookie(name){
var exp =
new Date();
exp.setTime(exp.getTime() - 1);
var cval=getCookie(name);
if
(cval!=
null
)
document.cookie= name +
"="
+cval+
";expires="
+exp.toGMTString()+
";path=/"
;
}
function getsec(str){
//alert(str);
var str1=str.substring(1,str.length)*1;
var str2=str.substring(0,1);
if (str2==
"s"
)
{
return str1*1000;
}
else if (str2==
"h"
)
{
return str1*60*60*1000;
}
else if (str2==
"d"
)
{
return str1*24*60*60*1000;
}
}
//获取Cookie
//var name = getCookie("name");
//var phone = getCookie("phone");
//
//if(phone != ""){
// $("input[name=phone]").val(phone);
//}
//if(name!="false"){
// $("input[name=name]").val(name);
//}
/***********************操作cookies的方法***************************/
|
Thank you for reading, hope to help everyone, thank you for the support of this site!
JavaScript Operation Cookies Detailed