在操作cookie的過程中走了一些彎路,cookie是不能跨域的,不過網上搜索到的函數,貌似能夠跨域。於是在IE6和maxthon1.6上不斷嘗試,終於以失敗告終.
<script type="text/javascript">
function setCookie(name,value,expiry,path,domain){
var nameString = name +"='"+ value+"'";
var expiryString = (expiry == null)?"" : ";expires ='" + expiry.toGMTString()+"'";
var pathString = (path == null) ? "":";path ='" + path+"'";
var domainString = (domain == null)?" ":";domain ='" + domain+"'";
var cookies=nameString + expiryString + pathString + domainString;
document.cookie = cookies;
}
</script>
上述函數中,如果傳入了domain和path的值,cookie都設置不成功:
var d=new Date(2008,12,31);
setCookie("test","test",d,"/ExampleApp",null);
setCookie("test2","test2",d,"/help",null);
setCookie("test2","test3",d,"/help",www.test.com.cn);
//-------------------------------
setCookie("test4","test4",d,null,null);
java的servlet中也是如此:
Cookie test5=new Cookie("test5","test1");
test5.setDomain("www.test1.com.cn");
test5.setPath("/help") ;
test5.setMaxAge(24*60*60);
response.addCookie(test5) ;
Cookie test6=new Cookie("test6","test6");
test6.setDomain(request.getServerName());
test6.setPath(request.getServletPath()) ;
test6.setMaxAge(24*60*60);
response.addCookie(test6) ;
//---------------------------
Cookie test7=new Cookie("test7","test7");
test7.setMaxAge(24*60*60);
response.addCookie(test7) ;
Cookie test8=new Cookie("test8","test8");
test8.setMaxAge(24*60*60);
response.addCookie(test8) ;
設置了path和domain也沒有報錯,但是這個cookie就沒有了。因此上述語句只成功設置了test4、test7、test8這三個cookie的值.下面是後臺可以讀取到的cookie的各個屬性的值,等號前面是屬性名稱,等號後面是屬性的值.:
DEBUG (CookieServlet.java:29) - name=test4,value='test4',domain=null,path=null
DEBUG (CookieServlet.java:29) - name=test7,value=test7,domain=null,path=null
DEBUG (CookieServlet.java:29) - name=test8,value=test8,domain=null,path=null
DEBUG (CookieServlet.java:29) - name=JSESSIONID,value=1ABAF39C37AD75BAE09435DE45239AEA,domain=null,path=null
這份代碼應該是正確的了 :-)
/**
* setCookie
* 如果多次調用,每次傳入不同的sName,就可設置多個cookie的值
*/
function setCookie(sName,sValue,dExpiry){
var sNameString = sName +"="+escape(sValue);
var sExpiryString = (dExpiry == null)?"":";expires =" + dExpiry.toGMTString();
document.cookie = sNameString + sExpiryString ;
}
// Retrieve the value of the cookie with the specified name.
function getCookie(sName){
// cookies are separated by semicolons
var aCookie = document.cookie.split(";");
for (var i=0; i < aCookie.length; i++){
// a name/value pair (a crumb) is separated by an equal sign
var aCrumb = aCookie[i].split("=");
if (sName == aCrumb[0])
return unescape(aCrumb[1]);
}
// a cookie with the requested name does not exist
return null;
}
// Delete the cookie with the specified name.
function delCookie(sName){
var sValue="delete";
document.cookie = sName + "=" + escape(sValue) + "; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
}