js对浏览器的Cookie保存和获取

时间:2024-03-10 07:26:39

//1.js保存cookie值到浏览器

var stringValue="";//需要存的数据

var oDate = new Date();
oDate.setTime(oDate.getTime() + 1* 24 * 60 * 60 * 1000);//设置过期时间
var cookieString = "CookieName=" + stringValue + ";expires=\'" + oDate.toGMTString() + ";path=/";
document.cookie = cookieString;//存cookie

//2.js获取cookie值

var cookieId = getCookie("CookieParentId");//取cookie

function getCookie(objName){//获取指定名称的cookie的值
var arrStr = document.cookie.split("; ");
for (var i = 0; i < arrStr.length; i++) {
var temp = arrStr[i].split("=");
if (temp[0] == objName){
return decodeURI(temp[1]);
}
}
}