JavaScript创建读取cookie代码示例【附:跨域cookie解决办法】
使用JavaScript 原生存取cookie代码示例:
var cookie = {
set : function(name, value, expires, path, domain, secure){
var date = new Date();
var days = '';
if(typeof expires == undefined){
days = 365 * 24 * 60 * 60 * 1000;
}else{
days = expires * 24 * 60 * 60 * 1000;
}
date.setTime(date.getTime() + days);
expires = date.toGMTString();
var cookieString = name + "=" + escape(value);
cookieString += (expires) ? "; expires=" + expires : "";
cookieString += (path) ? "; path=" + path : "";
cookieString += (domain) ? "; domain=" + domain : "";
cookieString += (secure) ? "; secure" : "";
document.cookie = cookieString;
},
get : function(key){
var cookies = document.cookie;
if(cookies.length > 0){
var key_start = document.cookie.indexOf(key+"=");
if(key_start !== -1){
var value_start = key_start + key.length + 1;
var value_end = cookies.indexOf(";",value_start);
if(value_end == -1) value_end = cookies.length;
return unescape(cookies.substring(value_start, value_end));
}
}
return "";
},
};
有的时候会遇到创建跨域名的cookie,比如想在自己所有的域名下同时设置cookie,一个很好的解决办法是:
在页面创建 <img src="http://other.domain/server.php" style="display:none">
标签,因为加载src资源会发起一个http请求,而我们可以在server.php中这么做:
<?php
setCookie('name','value',time() + 3600);
?>
比如你登陆Google再转到YouTube网站下发现是已经登陆的成功的状态,它用的就是这种方法。