1. 程式人生 > >javascript 設置cookie和取得cookie

javascript 設置cookie和取得cookie

asc name 結果 nco subst log 失效 bst ieda

代嗎實例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>cookie</title>
    <script>
        function  setCookie(name,value,expires,path,domain,secure)  {
            var cookieName=encodeURIComponent(name)+=+encodeURIComponent(value);
            
if(expires instanceof Date ) { cookieName+=;expires=+expires; } if(path) { cookieName+=;path=+path; } if(domain) {domain cookieName+=;domain=+domain; } if(secure) { cookieName
+=;secure; } document.cookie=cookieName; } function getCookie(name) { var cookieName=encodeURIComponent(name)+=; var cookieStart = document.cookie.indexOf(cookieName); if (cookieStart>-1) { var cookieEnd=document.cookie.indexOf(
;,cookieStart); if(cookieEnd==-1){ cookieEnd=documet.cookie.length; } cookieValue=decodeURIComponent(document.cookie.substring(cookieStart+cookieName.length,cookieEnd)); return cookieValue; } } alert(getCookie(user)); alert(getCookie(email)); alert(getCookie(url)); function setCookieDate(day) { //傳遞一個天數,比如傳遞7,就7天後失效 var date = null; if (typeof day == number && day > 0) { date = new Date(); date.setDate(date.getDate() + day); } else { throw new Error(您傳遞的天數不合法!必須是數字且大於0); } return date; } </script> </head> <p>設置cookie和取得cookie </p> </body> </html>

效果:

設置cookie

火狐設置下隱私選項我們可以看到cookie,在localhost中我們可以看到結果。

技術分享

cookie 中的user

技術分享

cookie 中的url

技術分享

cookie 中的email

技術分享

取得cookie

技術分享

16:45:06 2017-09-04

javascript 設置cookie和取得cookie