您的位置:首页 > Web前端 > JavaScript

JavaScript 设置、读取Cookie

2016-05-17 14:14 585 查看
1、设置Cookie

//设置cookie
function setCookie(cookieName, cookieValue, cookieExpires, cookiePath) {
cookieValue = escape(cookieValue);//编码latin-1
if (cookieExpires == "") {
var nowDate = new Date();
nowDate.setMonth(nowDate.getMonth() + 6);
cookieExpires = nowDate.toGMTString();
}
if (cookiePath != "") {
cookiePath = ";Path=" + cookiePath;
}
document.cookie = cookieName + "=" + cookieValue + ";expires=" + cookieExpires + cookiePath;
}


2、读取Cookie

//获取cookie
function getCookieValue(cookieName) {
var cookieValue = document.cookie;
var cookieStartAt = cookieValue.indexOf("" + cookieName + "=");
if (cookieStartAt == -1) {
cookieStartAt = cookieValue.indexOf(cookieName + "=");
}
if (cookieStartAt == -1) {
cookieValue = null;
}
else {
cookieStartAt = cookieValue.indexOf("=", cookieStartAt) + 1;
cookieEndAt = cookieValue.indexOf(";", cookieStartAt);
if (cookieEndAt == -1) {
cookieEndAt = cookieValue.length;
}
cookieValue = unescape(cookieValue.substring(cookieStartAt, cookieEndAt));//解码latin-1
}
return cookieValue;
}


3、调用,使用方法

function set()
{
setCookie("userName", "ck", "", "");
}
function read()
{
var value = getCookieValue("userName");
alert(value);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: