JS cookie的使用

來源:互聯網
上載者:User

標籤:

js設定cookie有很多種方法。

第一種:(這個是w3c官網的代碼)

<script>//設定cookiefunction setCookie(cname, cvalue, exdays,cpath) {//注:JS中的函數調用可以和定義時參數個數不同,調用時如不需要可以不加後兩個參數或最後一個參數)    var d = new Date();    d.setTime(d.getTime() + (exdays*24*60*60*1000));    var expires = "expires="+d.toUTCString();//到期時間用的是單詞 expites
  var path = "path="+cpath;//路徑設定,用的單詞是path document.cookie = cname + "=" + cvalue + "; " + expires+";"+path;} //擷取cookiefunction 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 "";}//清除cookie function clearCookie(name) { setCookie(name, "任一字元都可以,一般設為空白,關鍵是後面的時間", -1); } function checkCookie() { var user = getCookie("username"); if (user != "") { alert("Welcome again " + user); } else { user = prompt("Please enter your name:", ""); if (user != "" && user != null) { setCookie("username", user, 365); } }}checkCookie(); </script>

第二種:

<script>//JS操作cookies方法!//寫cookiesfunction setCookie(c_name, value, expiredays){     var exdate=new Date();    exdate.setDate(exdate.getDate() + expiredays);    document.cookie=c_name+ "=" + escape(value) + ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());   } //讀取cookiesfunction getCookie(name){    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");//Regex有很多種,這裡的是javascript的Regex(和php的正則不同)     if(arr=document.cookie.match(reg))         return (arr[2]);    else        return null;}//刪除cookiesfunction delCookie(name){    var exp = new Date();    exp.setTime(exp.getTime() - 1);    var cval=getCookie(name);    if(cval!=null)        document.cookie= name + "="+cval+";expires="+exp.toGMTString();}//使用樣本setCookie(‘username‘,‘Darren‘,30) alert(getCookie("username"));</script>

 第三個例子

<html> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    <head>         <script language="JavaScript" type="text/javascript">                         function addCookie(objName, objValue, objHours){//添加cookie                 var str = objName + "=" + escape(objValue);                 if (objHours > 0) {//為0時不設定到期時間,瀏覽器關閉時cookie自動消失                     var date = new Date();                     var ms = objHours * 3600 * 1000;                     date.setTime(date.getTime() + ms);                     str += "; expires=" + date.toGMTString();                 }                 document.cookie = str;                 alert("添加cookie成功");             }                         function getCookie(objName){//擷取指定名稱的cookie的值                 var arrStr = document.cookie.split("; ");                 for (var i = 0; i < arrStr.length; i++) {                     var temp = arrStr[i].split("=");                     if (temp[0] == objName)                         return unescape(temp[1]);                 }             }                         function delCookie(name){//為了刪除指定名稱的cookie,可以將其到期時間設定為一個過去的時間                 var date = new Date();                 date.setTime(date.getTime() - 10000);                 document.cookie = name + "=a; expires=" + date.toGMTString();             }                         function allCookie(){//讀取所有儲存的cookie字串                 var str = document.cookie;                 if (str == "") {                     str = "沒有儲存任何cookie";                 }                 alert(str);             }                         function $(m, n){                 return document.forms[m].elements[n].value;             }                         function add_(){                 var cookie_name = $("myform", "cookie_name");                 var cookie_value = $("myform", "cookie_value");                 var cookie_expireHours = $("myform", "cookie_expiresHours");                 addCookie(cookie_name, cookie_value, cookie_expireHours);             }                         function get_(){                 var cookie_name = $("myform", "cookie_name");                 var cookie_value = getCookie(cookie_name);                 alert(cookie_value);             }                         function del_(){                 var cookie_name = $("myform", "cookie_name");                 delCookie(cookie_name);                 alert("刪除成功");             }         </script>     </head>     <body>         <form name="myform">             <div>                 <label for="cookie_name">                     名稱                 </label>                 <input type="text" name="cookie_name" />             </div>             <div>                 <label for="cookie_value">                 值                 </lable>                 <input type="text" name="cookie_value" />             </div>             <div>                 <label for="cookie_expireHours">                 多少個小時到期                 </lable>                 <input type="text" name="cookie_expiresHours" />             </div>             <div>                 <input type="button" value="添加該cookie" onclick="add_()"/><input type="button" value="讀取所有cookie" onclick="allCookie()"/><input type="button" value="讀取該名稱cookie" onclick="get_()"/><input type="button" value="刪除該名稱cookie" onclick="del_()"/>             </div>         </form> </body> </html>

注意:

chrome瀏覽器在本地擷取不到cookie。必須在伺服器上才可以。如果是本地的話,你可以放到local的www目錄下面。

Google Chrome只支援線上網站的cookie的讀寫操作,對本地html的cookie操作是禁止的。所以下面的代碼如果你寫在一個本地的html檔案中,將彈出的對話方塊內容為空白。

document.cookie = "Test=cooo";
alert(document.cookie);

如果這個頁面是線上網站的內容,則會正常顯示cookie內容Test=cooo等等。

JS cookie的使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.