`
wangzi6hao
  • 浏览: 208859 次
  • 性别: Icon_minigender_1
  • 来自: sdf
社区版块
存档分类
最新评论

javascript cookie读写 javascript不能写非80端口cookie问题 javascript不能写localhost cookie问题

 
阅读更多

这几天在做方面的问题,因为网上有很大一堆的javascript cookie读写,所以自己也懒得去写那么多。直接找了一段还算工整的,测试一下,就用上了。但是问题来了。
1.javascript 不能写localhost的Cookie问题,不知道是不是bug,还是因为浏览器安全问题,反正是没有解决。但是在127.0.0.1下,又是可以写cookie的。费解ing....
2.javascript不能写非80端口cookie问题。经查是因为window.location.host 带了端口号,如127.0.0.1:8080,只要去掉:8080端口就好了。

//添加cookie
function setCookie(name,value,expires){
var path = "";
var domain = window.location.host;
domain = domain.substring(0, domain.indexOf(":"));//获取除端口外的url地址
var str=name+"="+escape(value);
if(expires!=""){
var date=new Date();
date.setTime(date.getTime()+expires*24*3600*1000);//expires 单位为天
str+="; expires="+date.toGMTString();
}
if(path!=""){
str+="; path="+path;//指定可访问cookie的目录
}
if(domain!=""){
str+="; domain="+domain;//指定可访问cookie的域
}
document.cookie=str;
}
//取得cookie
function getCookie(name){
var str=document.cookie.split("; ")
for(var i=0;i<str.length;i++){
var str2=str[i].split("=");
if(str2[0]==name)return unescape(str2[1]);
}
return "";
}
// 删除cookie
function delCookie(name){
var date=new Date();
date.setTime(date.getTime()-10000);
document.cookie=name+"=n;expire="+date.toGMTString();
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics