有時候咱們須要不一樣域名共享一個cookie,特別是一二級域名下。javascript
如用php自己就很簡單了。。以下便可php
setcookie('ywx001','測試用數據',time()+3600,'/','.xxx.com');
這樣無論是www.下仍是admin.下仍是xxx.xxx.com下均可以共享這個ywx001的值java
不過有時候可能你須要用js來存cookie,比php要稍微麻煩點。代碼以下:cookie
//設置cookie function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires="+d.toUTCString(); document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/; domain=.xxx.com"; } //獲取cookie function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1); if (c.indexOf(name) != -1) return c.substring(name.length, c.length); } return ""; } setCookie('ywx2','ceshishuju','1'); var a = getCookie('ywx2'); alert(a);
固然,這裏path和domain你也能夠寫爲參數,隨意便可。效果與上面php通常無二。dom