search

Home  >  Q&A  >  body text

javascript - js设置cookie过期时间设置无效?

我用js设置cookie的时候expires总是设置不成功

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

33

<code>window.onload = function(){

            var exp = new Date();

            exp.setTime(exp.getTime() + 30 * 24 * 60 * 60 * 1000);

            exp = exp.toGMTString();

            function setCookie(key, value, expires){

                var cookieStr = key + "=" + value;

                if(expires){

                    cookieStr += "; " + "max-age" + "=" + 1000;

                }

                // cookieStr += "; domain=baidu.com; path=/";

                document.cookie = cookieStr;

                console.log(document.cookie);

            }

            function getCookie(key){

                var cookieName = key + "=";

                var startIndex = document.cookie.indexOf(cookieName);

                var value = null;

                if(startIndex != -1){

                    var endIndex = document.cookie.indexOf(";", startIndex);

                    if(endIndex == -1){

                        endIndex = document.cookie.length;

                    }

                    value = document.cookie.substring(startIndex + cookieName.length, endIndex);

                }

                return value;

            }

            if(!getCookie("name")){

                document.getElementById("result").innerHTML = "Welcome!";

                setCookie("name", "xiaota", exp);

            }

            else{

                document.getElementById("result").innerHTML = "Welcome " + getCookie("name") + "!";

            }</code>

调用setCookie函数的时候,传入时间,console.log打印的结果并没有expires,不知道怎么回事。

黄舟黄舟2838 days ago937

reply all(2)I'll reply

  • ringa_lee

    ringa_lee2017-04-11 11:51:44

    其实过期时间已经设好了,但是max-ageexpires是不可见的。document.cookie里只能看到cookie的key:value

    目前大多数浏览器都可以查看cookie的max-ageexpires

    以Chrome为例:在devTool - Application - Storage - Cookies里面可以看到cookie的所有属性。

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-11 11:51:44

    function setCookie(name,value,days){//设置cookie

    1

    2

    3

    4

    <code>var d = new Date();

    d.setTime(d.getTime() + (days*24*60*60*1000));

    var expires = "expires="+d.toUTCString();

    document.cookie = name + "=" + value + "; " + expires;</code>

    }

    reply
    0
  • Cancelreply