面试题-js获取cookie中存储的值?

js获取cookie中存储的值?

1、cookie是浏览器提供的一种机制,它将document 对象的cookie属性提供给JavaScript。可以由JavaScript对其进行控制,而并不是JavaScript本身的性质。cookie是存于用户硬盘的一个文件,这个文件通常对应于一个域名,当浏览器再次访问这个域名时,便使这个cookie可用。因此,cookie可以跨越一个域名下的多个网页,但不能跨越多个域名使用。

2、不同的浏览器对cookie的实现也不一样,但其性质是相同的。例如在Windows 2000以及Windows xp中,cookie文件存储于documents and settings\userName\cookie\文件夹下。通常的命名格式为:userName@domain.txt。

3、cookie机制将信息存储于用户硬盘,因此可以作为全局变量,这是它最大的一个优点。它可以用于以下几种场合。

(1)保存用户登录状态。例如将用户id存储于一个cookie内,这样当用户下次访问该页面时就不需要重新登录了,现在很多论坛和社区都提供这样的功能。 cookie还可以设置过期时间,当超过时间期限后,cookie就会自动消失。因此,系统往往可以提示用户保持登录状态的时间:常见选项有一个月、三个 月、一年等。

(2)跟踪用户行为。例如一个天气预报网站,能够根据用户选择的地区显示当地的天气情况。如果每次都需要选择所在地是烦琐的,当利用了 cookie后就会显得很人性化了,系统能够记住上一次访问的地区,当下次再打开该页面时,它就会自动显示上次用户所在地区的天气情况。因为一切都是在后 台完成,所以这样的页面就像为某个用户所定制的一样,使用起来非常方便。

(3)定制页面。如果网站提供了换肤或更换布局的功能,那么可以使用cookie来记录用户的选项,例如:背景色、分辨率等。当用户下次访问时,仍然可以保存上一次访问的界面风格。

(4)创建购物车。正如在前面的例子中使用cookie来记录用户需要购买的商品一样,在结账的时候可以统一提交。例如淘宝网就使用cookie记录了用户曾经浏览过的商品,方便随时进行比较。

4、当然,上述应用仅仅是cookie能完成的部分应用,还有更多的功能需要全局变量。cookie的缺点主要集中于安全性和隐私保护。主要包括以下几种:

(1)cookie可能被禁用。当用户非常注重个人隐私保护时,他很可能禁用浏览器的cookie功能;
(2)cookie是与浏览器相关的。这意味着即使访问的是同一个页面,不同浏览器之间所保存的cookie也是不能互相访问的;
(3)cookie可能被删除。因为每个cookie都是硬盘上的一个文件,因此很有可能被用户删除;
(4)cookie安全性不够高。所有的cookie都是以纯文本的形式记录于文件中,因此如果要保存用户名密码等信息时,最好事先经过加密处理。

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

6、首先,我们会创建一个可在 cookie 变量中存储访问者姓名的函数:

function Setcookie (name, value){ 
    //设置名称为name,值为value的Cookie
    var expdate = new Date();   //初始化时间
    expdate.setTime(expdate.getTime() + 30 * 60 * 1000);   //时间
    document.cookie = name+"="+value+";expires="+expdate.toGMTString()+";path=/";
   //即document.cookie= name+"="+value+";path=/";   
   //时间可以不要,但路径(path)必须要填写,因为JS的默认路径是当前页,如果不填,此cookie只在当前页面生效!
}

7、上面这个函数中的参数存有 cookie 的名称、值以及过期天数。在上面的函数中,我们首先将天数转换为有效的日期,然后,我们将 cookie 名称、值及其过期日期存入 document.cookie 对象。之后,我们要创建另一个函数来检查是否已设置 cookie:

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 ""
}

8、上面的函数首先会检查 document.cookie 对象中是否存有 cookie。假如 document.cookie 对象存有某些 cookie,那么会继续检查我们指定的 cookie 是否已储存。如果找到了我们要的 cookie,就返回值,否则返回空字符串。最后,我们要创建一个函数,这个函数的作用是:如果 cookie 已设置,则显示欢迎词,否则显示提示框来要求用户输入名字。

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)
    }
  }
}

9、一个完整实例

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>无标题文档</title>
<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>

10、上面讲到了cookie的创建我们现在来看一个利用cookie保存浏览记录实例。浏览记录的显示是从cookie里读出来,然后解析成json,生成html元素。因为用户可能会同时打开好几个页面,这几个页面上可能都有浏览记录,为了使即使显示浏览记录,每秒中刷新一次。要用到2个js文件,history.js,关键的聊天记录保存和读取代码。json.js,对json进行处理。history.js

var addHistory=function(num,id){
    stringCookie=getCookie('history');
    var stringHistory=""!=stringCookie?stringCookie:"{history:[]}";
    var json=new JSON(stringHistory);
    var e="{num:"+num+",id:"+id+"}";
    json['history'].push(e);//添加一个新的记录
    setCookie('history',json.toString(),30);
}

//显示历史记录
var DisplayHistory=function(){
    var p_ele=document.getElementById('history');
  	while (p_ele.firstChild) {
    		p_ele.removeChild(p_ele.firstChild);
    }

    var historyJSON=getCookie('history');
    var json=new JSON(historyJSON);
    var displayNum=6;
    for(i=json['history'].length-1;i>0;i--){
        addLi(json['history'][i]['num'],json['history'][i]['id'],"history");
        displayNum--;
        if(displayNum==0){break;}
    }
}

//添加一个li元素
var addLi=function(num,id,pid){
    var a=document.createElement('a');
    var href='product.action?pid='+id;
    a.setAttribute('href',href);
    var t=document.createTextNode(num);
    a.appendChild(t);
    var li=document.createElement('li');
    li.appendChild(a);
    document.getElementById(pid).appendChild(li);
}

//添加cookie
var setCookie=function(c_name,value,expiredays)
{
    var exdate=new Date()
    exdate.setDate(exdate.getDate()+expiredays)
    cookieVal=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
		//alert(cookieVal);
    document.cookie=cookieVal;
}

//获取cookie
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
								//document.write(document.cookie.substring(c_start,c_end)+"<br>");
        		return unescape(document.cookie.substring(c_start,c_end))
        } 
		}
    return ""
}

11、json文件

var JSON = function(sJSON){
    this.objType = (typeof sJSON);
    this.self = [];
    (function(s,o){for(var i in o){o.hasOwnProperty(i)&&(s[i]=o[i],s.self[i]=o[i])};})(this,(this.objType=='string')?eval('0,'+sJSON):sJSON);
}

JSON.prototype = {
    toString:function(){
        return this.getString();
    },
    valueOf:function(){
        return this.getString();
    },
    getString:function(){
        var sA = [];
        (function(o){
            var oo = null;
            sA.push('{');
            for(var i in o){
                if(o.hasOwnProperty(i) && i!='prototype'){
                    oo = o[i];
                    if(oo instanceof Array){
                        sA.push(i+':[');
                        for(var b in oo){
                            if(oo.hasOwnProperty(b) && b!='prototype'){
                                sA.push(oo[b]+',');
                                if(typeof oo[b]=='object') arguments.callee(oo[b]);
                            }
                        }
                        sA.push('],');
                        continue;
                    }else{
                        sA.push(i+':'+oo+',');
                    }
                    if(typeof oo=='object') arguments.callee(oo);
                }
            }
            sA.push('},');
        })(this.self);
        return sA.slice(0).join('').replace(/[object1object],/ig,'').replace(/,}/g,'}').replace(/,]/g,']').slice(0,-1);
    },
    push:function(sName,sValue){
        this.self[sName] = sValue;
        this[sName] = sValue;
    }
}

12、html文档

<script type="text/javascript" src="../js/json.js"></script>
<script type="text/javascript" src="../js/history.js"></script>
<ul id="history"></ul>
<script> 
  addHistory(15810782304,2);
  addHistory(64654665,2);
  addHistory(6843212,2);
  addHistory(84984432521,2);
  setInterval("DisplayHistory()",1000);
</script>
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

互联网小队

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值