HTML5/CSS3跨平台开发技术分享(二)

来源:互联网 发布:淘宝按重量设置运费 编辑:程序博客网 时间:2024/06/04 18:28

js操作cookie存取数据实例与分析(二)

在上篇文章里,说cookie设置的时候,可以一次往cookie里放入几个值,用分号和空格"; " 隔开。我们用下上面的例子试下:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>cookie test</title>
<meta name="keywords" content="">
<meta name="description" content="">
<script>
function setCookie() {
document.cookie="userName=lzl; serId=123";
}
function showCookie() {
if (document.cookie)
{
    alert(document.cookie)
}
else{alert("document.cookie 不存在");}
}
</script>
</head>

<body>
 <input type="button" onclick="setCookie()" value="设置cookie"/>
 <input type="button" onclick="showCookie()"value="显示cookie"/>
</body>
</html>

发现只在cookie里存入了第一个值userName,第二个值并没有存入,

这是因为在cookie的设置中,不允许出现分号,都好,空格,等号等符号,我们处理的方法是使用escape()函数进行编码。把特殊字符都表示成为%xx的形式,其中xx是十六进制数。比如说空格经过escape()方法编码以后返回"%20"。在读取值时,我们用unescape()方法进行解码,可以还原为我们想设置的样式。如下所示

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>cookie test</title>
<meta name="keywords" content="">
<meta name="description" content="">
<script>
function setCookie() {
document.cookie="userName"+escape("=lzl; ")+"userId"+escape("=123");
}
function showCookie() {
if (document.cookie)
{
    var ck = unescape(document.cookie);
    alert(ck)
}
else{alert("document.cookie 不存在");}
}
</script>
</head>

<body>
 <input type="button" onclick="setCookie()" value="设置cookie"/>
 <input type="button" onclick="showCookie()"value="显示cookie"/>
</body>
</html>

显示效果如下:


实际上如果是这种简单的设置,我们用第一种方式设置比较方便。

 

在实际的操作中,可能有很多cookie名/值对。我们需要取其中的一个,但是cookie读取的时候一下会都读取出来,所以要用字符串的操作截取出来。cookie实际的存储是这样的 cookie="userName=lzl; uerId=123; aaa=bbb; cccc=dddd"也就是说,我们通过“; ”分号空格先分割下就可以把cookie的不同名值对。然后找到对应值。如下所示:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>cookie test</title>
<meta name="keywords" content="">
<meta name="description" content="">
<script language="JavaScript" type="text/javascript"> 
<!-- 
//设置两个cookie 
document.cookie="userName=lzl"; 
document.cookie="userId=123"; 
//获取cookie字符串 
var strCookie=document.cookie; 
//将多cookie切割为多个名/值对 
var arrCookie=strCookie.split("; "); 
var userId; 
//遍历cookie数组,处理每个cookie对 
for(var i=0;i<arrCookie.length;i++){ 
var arr=arrCookie[i].split("="); 
//找到名称为userId的cookie,并返回它的值 
if("userId"==arr[0]){ 
userId=arr[1]; 
break; 


alert("userId的值是 "+userId); 
//--> 
</script> 
<body>
</body>
</html>

显示结果如下:


下篇文章继续~今天先写到这里了。

摘自:http://hi.baidu.com/kuntakinte/item/863c01ff6574cfc10dd1c819

0 0
原创粉丝点击