其他教程

其他教程

Products

当前位置:首页 > 其他教程 >

JavaScript怎样操作COOKIE ?

GG网络技术分享 2025-03-18 16:17 0


以前工作,不忙的时候,用js面向对象的思想,写了一个操作cookie的类!

案例如下:

cache.class.js

/**提供客户端cookie操作类

*

* @param string uniqueN 唯一标识

*

*/

var cacheLY = function(uniqueN){

var uniqueN = (typeof(uniqueN) != \"string\") ? \"\" : \"uniqueN_\" + uniqueN + \"_\";

setCookie = function(name, value){

var Days = 1;

var exp = new Date();

exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);

document.cookie = name + \"=\" + escape(this.encode(value)) + \";expires=\" + exp.toGMTString();

}

getCookie = function(name){

var arr = document.cookie.match(new RegExp(\"(^| )\" + name + \"=([^;]*)(;|$)\"));

if (arr != null)

return this.unencode(unescape(arr[2]));

return null;

}

delCookie = function(name){

var exp = new Date();

exp.setTime(exp.getTime() - 1);

var tem = this.getCookie(name);

if (tem != null)

document.cookie = \"name=\" + tem + \";expires=\" + exp.toGMTString();

}

encode = function(str){

var temstr = \"\";

var i = str.length - 1;

for (i; i >= 0; i--) {

temstr += str.charCodeAt(i);

if (i)

temstr += \"a\";

}

return temstr;

}

unencode = function(str){

var strarr = \"\";

var temstr = \"\";

strarr = str.split(\"a\");

var i = strarr.length - 1;

for (i; i >= 0; i--) {

temstr += String.fromCharCode(eval(strarr[i]));

}

return temstr;

}

return {

setValue: function(text){

setCookie(uniqueN, text);

},

clearCache: function(name){

delCookie(name);

},

loadCache: function(){

var temvalue = getCookie(uniqueN);

return temvalue;

}

}

}

index.html

<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">

<html>

<head>

<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\">

<title>js控制cookie实现客户端缓存</title>

<script src=\"cache.class.js\" type=\"text/javascript\">

</script>

</head>

<body>

<div id=\"nihao\">

</div>

<script type=\"text/javascript\">

/*

* @param string tem 需要缓存的数据

* @param object cache 缓存对象

* @param string re 得到的缓存数据

*

*/

var tem = \'<div id=\"d\"><br><br><br>奥特曼在线</div>\';

var cache = new cacheLY(\"123\");

cache.setValue(tem);

var re = cache.loadCache();

document.getElementById(\"nihao\").innerHTML = re;

</script>

</body>

</html>

标签: 缓存 操作

提交需求或反馈

Demand feedback