zoukankan      html  css  js  c++  java
  • JavaScript Cookies使用

        Cookie 是个存储在客户端(浏览器)记录信息确定用户身份的小文本文件,可以用来跟踪用户当前登陆状态和用户浏览页面的次数,记录用户输入的文本信息,也可以在页面间传递变量,记录用户一些行为。

    当浏览器运行时,存储在 RAM 中。一旦你从该网站或网络服务器退出,Cookie 也可存储在计算机的硬盘上。当访客结束其浏览器对话时,即终止的所有 Cookie。

    与cookies相对应的,另一种记录客户状态的机制是session,保存在服务器端,使用起来比cookies简单。Session对应的类为javax.servlet.http.HttpSession类。Session与 Cookie一样,也是一种key-value的键值对,通过getAttribute(Stringkey)和setAttribute(String key,Objectvalue)方法读写用户状态信息。Servlet里通过request.getSession()方法获取该客户的Session。

    JS设置cookies、检查cookies示例代码:

    <html>
    <head>
    <script type="text/javascript">
    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 ""
    }
    
    function setCookie(c_name,value,expiredays)
    {
    var exdate=new Date()
    exdate.setDate(exdate.getDate()+expiredays)
    document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
    }
    
    function checkCookie()
    {
    username=getCookie('username')
    if (username!=null && username!="")
      {alert('Welcome again '+username+'!')}
    else 
      {
      username=prompt('Please enter your name:',"")
      if (username!=null && username!="")
        {
        setCookie('username',username,365)
        }
      }
    }
    </script>
    </head>
    
    <body onLoad="checkCookie()">
    </body>
    </html>
  • 相关阅读:
    Python 去掉文本中空行
    Pandas常用操作方法
    Numpy常用操作方法
    Python获取指定路径下所有文件的绝对路径
    Python获取指定目录下所有子目录、所有文件名
    Pycharm选中代码无法Backspace直接删除
    Redis常用命令(一)
    在eclipse程序中设置的断点上有一个斜杠,正常启动debug不能够跳转到debug页面,怎么解决
    常见的几种网络广告模式
    struts2中拦截器与过滤器的区别
  • 原文地址:https://www.cnblogs.com/K2154952/p/5935570.html
Copyright © 2011-2022 走看看