javascript系列之Cookie

一.欢迎来到我的酒馆

1.1什么是cookie?
      web浏览器和服务器之间使用HTTP协议进行通信,HTTP是一种无状态的通信协议。但对于一个商业网站,在不同的网页之间维护session信息很有必要。例如,一个用户在完成许多张网页之后完成了注册,但是如何维护用户的session信息涉及到所有的网页。
      在很多种情况下,在记录和跟踪用户的喜好,付款,任务和其他用于提升用户体验的必要数据上,使用cookie是最有效的办法。
1.2 cookie是如何工作的?
      你的服务器会以cookie的形式向用户的浏览器发送数据。这时,用户的浏览器可能会接收这个cookie,如果接收了,它会以文本的形式保存在用户的硬盘里。现在,当你的用户访问你网站的其他网页的时候,浏览器会将相同的cookie发送到服务器进行检索,一旦检索成功后,你的服务器会记住之前存储的内容。
cookie是包含5个可变长度字段的、纯文本的数据记录

  • Expires - Cookie的过期日期。如果这个值为空、当用户关闭浏览器时,cookie将会过期,
  • Domain - 你网站的域名。
  • Path - 设置cookie的目录或网页的路径。如果你想从目录或网页中检索cookie,可能为空。
  • Seecure - 如果这个字段包含secure关键字,这时候只能使用安全服务器检索cookie。如果此字段为空,则不存在此类限制。
  • Name=Value - cookie以key-value键值对的形式检索和设置。

1.3 cookie最初是被用来设计CGI程序。cookie中包含的数据在web浏览器和web服务器之间自动传输,因此服务器上的CGI脚本可以读取和写入存储在客户端的cookie的值。
javasript同样可以使用DOM对象操作cookie,javascript可以读取、创建、修改和删除应用在当前网页的cookie。

二.存储cookie

2.1存储cookie
      创建cookie最简单的方法是将一个字符串赋值给document.cookie对象,如下面的例子:

document.cookie = "key1 = value1;key2 = value2;expires = date"

expires属性不是必要的。如果你写了expires属性提供了一个有效的日期或时间,这时候cookie会在指定的时间过期,cookie过期之后将不可以访问。
注意:cookie值不包括分号,逗号和空格。因此,在存储cookie值之前你可以使用JavaScript的escape()函数来编码cookie值,如果你使用了这种发方法,当你在读取cookie值的时候,你也需要使用javascript unescape()方法。
2.2 例子
下面的例子,在cookie中存储了用户的名字:

<!DOCTYPE html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        function WriteCookie(){
            if(document.myform.customer.value == ""){
                alert("Enter some value!");
                return;
            }
            // escape()函数用于编码一个字符串并返回一个新的字符串
            cookievalue = escape(document.myform.customer.value) + ";";
            document.cookie = "name=" + cookievalue;
            document.cookie = "name=" +"xxx;";
            document.cookie = "age=18;";
            document.cookie = "address=Green road;";

            //document.write("Setting cookies: " + "name=" + cookievalue);
            document.write(document.cookie);
        }
    </script>
</head>
<body>
    <form name="myform" action="">
        Enter name : <input type="text" name="customer">
        <input type="button" value="set cookie" onclick="WriteCookie()">
    </form>
</body>
</html>

三.读取cookie

       3.1读取cookie和写cookie一样简单,因为document.cookie对象的值就是cookie。因此你可以使用这个字符串无论何时你想要访问cookie。document.cookie的值为一个字符串,并且用分号隔开一个个键值对,键名为cookie的名字,值为cookie的值。
你可以使用split()函数分割字符串成一个个键值对。
3.2 读取cookie例子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        function ReadCookie(){

            //准备cookie
            document.cookie = "name=" + "xxxx;";
            document.cookie = "age=" + "90;";
            document.cookie = "address=" + "Green Road;";

            // 读取所有的cookie
            let allcookies = document.cookie;
            document.write("All cookies: "+allcookies + "<br/>");

            //分割所有的cookie字符串
            let cookiearray = allcookies.split(';');

            //拿到所有的cookie键值对
            for(var i = 0;i<cookiearray.length;i++){
                let name = cookiearray[i].split('=')[0];
                let value = cookiearray[i].split('=')[1];
                document.write("Key is: "+name+" and Value is: " + value + "<br/>");
            }
        }
    </script>
</head>
<body>
    <form name="myform" action="">
        <p>点击下面的按钮读取cookie</p>
        <input type="button" value="get cookie" onclick="ReadCookie()">
    </form>
</body>
</html>

注意:length是array类的一个方法,它会返回一个数组的长度。我们会单独讲解array。这里尝试着理解一下。

四.设置cookie的最后期限

       4.1你可以通过设置到期日期并将到期日期保存在cookie中,将cookie的寿命延长到当前浏览器之后,这可以通过将"expire"属性设置为日期来完成。
4.2 下面的例子将cookie的到期日期延长了一个月:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        function WriteCookie(){
            //获取一个日期对象
            let now = new Date();
            //设置一个日期为当前日期的一个月之后
            now.setMonth( now.getMonth() +1);

            //获取输入框中的值
            cookievalue = escape(document.myform.customer.value)+";";

            //设置cookie
            document.cookie = "name="+ cookievalue;
            
            //设置cookie到期日期
            document.cookie = "expires="+now.toUTCString();
            document.write("Setting cookie: " + "name=" + cookievalue);
            document.write("<br/>");
            document.write(document.cookie);

        }
    </script>
</head>
<body>
  <form name="myform" action="">
    Enter name: <input type="text" name="customer">
    <input type="button" value="Set cookie" onclick="WriteCookie()">
  </form>
</body>
</html>

五.删除cookie

       5.1有时候,你会想删除一个cookie,cookie删除后在读取cookie的时候会返回空。要实现这个功能,你只需要设置cookie的到期日期为一个过去的时间。
5.2 下面的例子演示了删除一个cookie,通过将cookie的到期日期设置为一个过去的日期。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        function WriteCookie() {
            //创建一个日期对象
            let now = new Date();
            //设置当前日期为过去的一个月的日期
            now.setMonth(now.getMonth() - 1);

            //将form表单的input输入框的值编码
            cookievalue = escape(document.myform.customer.value) + ";";

            // 将输入框中的内容保存到cookie里
            document.cookie = "name=" + cookievalue;
            //设置cookie的到期日期
            document.cookie = "expires=" + now.toUTCString() + ";";
            document.write("Setting cookie: " + "name=" + cookievalue);
            document.write("<br/>");
            //document.write(document.cookie);

            // 拿到cookie的键值对
            let cookiearray = document.cookie.split(';');
            for(let i=0;i<cookiearray.length;i++){
                let name = cookiearray[i].split('=')[0];
                let value = cookiearray[i].split('=')[1];
                document.write("key= " + name +", value="+value+"<br/>");
            }
        }
    </script>
</head>
<body>
    <form name="myform" action="">
        Enter name: <input type="text" name="customer">
        <input type="button" value="Set Cookie" onclick="WriteCookie()">
    </form>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值