js读写cookie

来源:互联网 发布:手机数据备份软件 编辑:程序博客网 时间:2024/05/20 02:28

//写cookie

function setCookie(name, value, hours,cookiePath) {//过期时间为hours小时

var expire = "";

if (hours != null) {

expire = new Date((new Date()).getTime() + hours * 3600000);

expire = "; expires=" + expire.toGMTString();

}

var path="";//在不同页面设置path不一致时,在cookie中会存在多个同一name对应的cookie,path不一致,读取时可能会出错

if(cookiePath!=null){

path="; path="+cookiePath;

}

document.cookie = name + "=" + escape(value) + expire+path;

}

//读cookie

function getCookie(name) {

var cookieValue = "";

var search = name + "=";

if (document.cookie.length > 0) {

offset = document.cookie.indexOf(search);

if (offset != -1) {

offset += search.length;

end = document.cookie.indexOf(";", offset);

if (end == -1)

end = document.cookie.length;

cookieValue = unescape(document.cookie.substring(offset, end))

}

}

return cookieValue;

}

原创粉丝点击