为了账号安全,请及时绑定邮箱和手机立即绑定

请问JS 该怎么保存Cookie~~?

请问JS 该怎么保存Cookie~~?

鸿蒙传说 2019-07-03 07:03:52
JS 怎么保存Cookie~~
查看完整描述

4 回答

?
神不在的星期二

TA贡献1963条经验 获得超6个赞

js保存COOKIE,直接给document加上cookie就可以了,但是一般如果单个的加会很麻烦所以一般会直接写好一个函数,可以直接操作cookie,这样就很方便了

setCookie这个是写入cookie,第一个是名称,第二个是cookie值,第三个是过期时间

getCookie这个是查找cookie;

removeCookie这是你需要删除的cookie;

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

function setCookie(name, value, iDay) 

{

    var oDate=new Date();

     

    oDate.setDate(oDate.getDate()+iDay);

     

    document.cookie=name+'='+encodeURIComponent(value)+';expires='+oDate;

}

 

function getCookie(name)

{

    var arr=document.cookie.split('; ');

    var i=0;

    for(i=0;i<arr.length;i++)

    {

        //arr2->['username', 'abc']

        var arr2=arr[i].split('=');

         

        if(arr2[0]==name)

        {  

            var getC = decodeURIComponent(arr2[1]);

            return getC;

        }

    }

     

    return '';

}

 

function removeCookie(name)

{

    setCookie(name, '1', -1);

}


查看完整回答
反对 回复 2019-07-07
?
慕工程0101907

TA贡献1887条经验 获得超5个赞

<!DOCTYPE HTML>

<html lang="en-US">

<head>

<meta charset="UTF-8">

<meta name="keywords" content="白菜编辑部">

<title>白菜编辑部</title>

<style type="text/css">

</style>

<script type="text/javascript">

    function readCookie (name)

    {

        var cookieValue = "";

        var search = name + "=";

        if (document.cookie.length > 0)

        {

            offset = document.cookie.indexOf (search);

            if (offset != -1)

            {

                offset += search.length;

                end = document.cookie.indexOf (";", offset);

                if (end == -1)

                    end = document.cookie.length;

                cookieValue = unescape (document.cookie.substring (offset, end))

            }

        }

        return cookieValue;

    }

    function writeCookie (name, value, hours)

    {

        var expire = "";

        if (hours != null)

        {

            expire = new Date ((new Date ()).getTime () + hours * 3600000);

            expire = "; expires=" + expire.toGMTString ();

        }

        document.cookie = name + "=" + escape (value) + expire;

    }

      

    writeCookie ("myCookie", "my name", 24);

    alert (readCookie ("myCookie"));

</script>

</head>

<body>

</body>

</html>

 


查看完整回答
反对 回复 2019-07-07
  • 4 回答
  • 0 关注
  • 1486 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信