搜尋

首頁  >  問答  >  主體

JavaScript教學:利用JavaScript建立和讀取cookie中的值

<p>如何在JavaScript中建立和讀取cookie的值? </p>
P粉752290033P粉752290033471 天前509

全部回覆(2)我來回復

  • P粉132730839

    P粉1327308392023-08-22 00:26:42

    簡約而功能齊全的ES6方法:

    const setCookie = (name, value, days = 7, path = '/') => {
      const expires = new Date(Date.now() + days * 864e5).toUTCString()
      document.cookie = name + '=' + encodeURIComponent(value) + '; expires=' + expires + '; path=' + path
    }
    
    const getCookie = (name) => {
      return document.cookie.split('; ').reduce((r, v) => {
        const parts = v.split('=')
        return parts[0] === name ? decodeURIComponent(parts[1]) : r
      }, '')
    }
    
    const deleteCookie = (name, path) => {
      setCookie(name, '', -1, path)
    }

    回覆
    0
  • P粉785905797

    P粉7859057972023-08-22 00:02:24

    這裡是用來建立和取得cookie的函數。

    function createCookie(name, value, days) {
        var expires;
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toGMTString();
        }
        else {
            expires = "";
        }
        document.cookie = name + "=" + value + expires + "; path=/";
    }
    
    function getCookie(c_name) {
        if (document.cookie.length > 0) {
            c_start = document.cookie.indexOf(c_name + "=");
            if (c_start != -1) {
                c_start = c_start + c_name.length + 1;
                c_end = document.cookie.indexOf(";", c_start);
                if (c_end == -1) {
                    c_end = document.cookie.length;
                }
                return unescape(document.cookie.substring(c_start, c_end));
            }
        }
        return "";
    }

    回覆
    0
  • 取消回覆