Cookie的使用之保存与获取代码示例
代码为设置Cookie和获取Cookie方法的例子
代码如下:
function SetUserCookie() {
//取用户名
var usr = document.getElementById('user').value;
var expdate = new Date();
//当前时间加上两周的时间
expdate.setTime(expdate.getTime() + 14 * (24 * 60 * 60 * 1000));
//将最后一个用户信息写入到Cookie
SetCookie("49BA-C005-7D-OADOC-5B-USER",usr,expdate);
}
function GetUserCookie() {
var id = "49BA-C005-7D-OADOC-5B-USER";//GUID标识符
var usr = GetCookie(id);
if (usr != null) {
document.getElementById('userid').value = usr;
}
}
//写入到Cookie
function SetCookie(name, value, expires) {
var argv = SetCookie.arguments;
//本例中length = 3
var argc = SetCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : null;
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;
document.cookie = name + "=" + escape(value) + ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + ((path == null) ? "" : ("; path=" + path)) + ((domain == null) ? "" : ("; domain=" + domain)) + ((secure == true) ? "; secure" : "");
}
//取Cookie的值
function GetCookie(name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
//alert(j);
if (document.cookie.substring(i, j) == arg) return getCookieVal(j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function getCookieVal(offset) {
var endstr = document.cookie.indexOf(";", offset);
if (endstr == -1) endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}