JavaScript怎样操作COOKIE ?

分类:JavaScript | 作者:凹凸曼 | 发表于2011/04/12 JavaScript怎样操作COOKIE ?已关闭评论

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

    案例如下:

     cache.class.js


 

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

 *
 * @param string uniqueN 唯一标识
 *
 * @author (凹凸曼)lyc
 * @email jar-c@163.com
 *
 */
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>

本文出自 “凹凸曼” 博客,请务必保留此出处 http://www.apoyl.com/?p=478

Tag:

日志信息 »

该日志于2011-04-12 01:15由 凹凸曼 发表在JavaScript分类下, 评论已关闭。

目前盖楼

抱歉,评论被关闭

« »