zoukankan      html  css  js  c++  java
  • javascript中设置可取cookie的方法

    在这个例子中我们要创建一个存储访问者名字的 cookie。当访问者首次访问网站时,他们会被要求填写姓名。名字会存储于 cookie 中。当访问者再次访问网站时,他们就会收到欢迎词。

    取cookie的时候使用的两种方法。

    View Code
    1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    2  <html xmlns="http://www.w3.org/1999/xhtml">
    3  <!--要实现的功能:第一次登录时需要填写姓名,第二次在登录的时候就会出现欢迎词。-->
    4  <head>
    5 <title>设置cookie</title>
    6 <script type="text/javascript">
    7 function getCookie(c_name) {
    8 // if (document.cookie.length > 0) {
    9 // c_start = document.cookie.indexOf(c_name + "=")
    10 // if (c_start != -1) {
    11 // c_start = c_start + c_name.length + 1
    12 // c_end = document.cookie.indexOf(";", c_start)
    13 // if (c_end == -1) c_end = document.cookie.length
    14 // return unescape(document.cookie.substring(c_start, c_end))
    15 // }
    16 // }
    17 //
    18 // return "" 被注释掉的方式也可以。
    19 if (document.cookie.length > 0) {
    20
    21 var arrstr = document.cookie.split(";")
    22 var strid;
    23 for(var i = 0; i<arrstr.length; i++)
    24 {
    25 var str = arrstr[i].split("=");
    26 if ("username" == str[0])
    27 {
    28 strid = str[1];
    29 }
    30 break;
    31 }
    32 return strid;
    33 }
    34 return ""
    35
    36 }
    37
    38 function setCookie(c_name, value, expiredays) {
    39 var exdate = new Date()
    40 exdate.setDate(exdate.getDate() + expiredays)
    41 document.cookie = c_name + "=" + escape(value) +
    42 ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString())
    43 }
    44
    45 function checkCookie() {
    46 username = getCookie('username')
    47 if (username != null && username != "")
    48 { alert('Welcome again ' + username + '!') }
    49 else {
    50 username = prompt('Please enter your name:', "")
    51 if (username != null && username != "") {
    52 setCookie('username', username, 365)
    53 }
    54 }
    55 }
    56 </script>
    57 </head>
    58
    59 <body onload="checkCookie()">
    60 </body>
    61
    62 </html>

    学习自:http://www.w3school.com.cn/js/js_cookies.asp

         和:http://zhidao.baidu.com/question/72613073

  • 相关阅读:
    关于用mybatis调用存储过程时的入参和出参的传递方法
    Bootstrap系列 -- 35. 按钮的向下向上三角形
    Bootstrap系列 -- 34. 按钮下拉菜单
    Bootstrap系列 -- 33. 等分按钮
    Bootstrap系列 -- 32. 按钮垂直分组
    Bootstrap系列 -- 31.嵌套分组
    Bootstrap系列 -- 30. 按钮工具栏
    Bootstrap系列 -- 29. 按钮组
    Bootstrap系列 -- 28. 下拉菜单状态
    Bootstrap系列 -- 27. 下拉菜单对齐方式
  • 原文地址:https://www.cnblogs.com/zhouxiuquan/p/1987937.html
Copyright © 2011-2022 走看看