论坛首页 Web前端技术论坛

JS操作COOKIE

浏览 12413 次
锁定老帖子 主题:JS操作COOKIE
精华帖 (0) :: 良好帖 (0) :: 新手帖 (18) :: 隐藏帖 (1)
作者 正文
   发表时间:2009-11-17  
//set cookie
   
function setcookie(name,value){
    var Days = 30;
    var exp  = new Date();
    exp.setTime(exp.getTime() + Days*24*60*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}

function getcookie(name){
    var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)")); 
    if(arr != null){
        return unescape(arr[2]);
    }else{
        return "";
    }
}

function delcookie(name){
    var exp = new Date(); 
    exp.setTime(exp.getTime() - 1);
    var cval=getCookie(name);
    if(cval!=null) document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}

//delcookie("GD-cms");
if (document.cookie != "") { 
    setcookie("GD-cms", "gae-django-cms");
}
alert(getcookie("GD-cms")); 
 


原文
   发表时间:2009-11-18  
价值不高。

第一,不○○,现在大家好像比较重视这个。
第二,功能也不全面,cookie的有效时间应该做为参数传入,而不是写死在函数里面。

理论上至少应该是这样:

Cookie={
    set:function(params){...}
    ,get:function(params){...}
    ,remove:function(params){...}
}

但我不喜欢又是get又是set的,我喜欢合二为一,就像jquery那样,取值和设置值是同一个方法,只是参数不同。只传一个key就是取值,同时传了value就是设置。
所以要这样:
Cookie={
    item:function(params){...}
}
用的时候可以这样:
Cookie.item(key, value); //设置cookie
Cookie.item({key:key, value:value, expires:expires, domain:domain}); //设置cookie
var value = Cookie.item(key); //获取cookie
Cookie.item(key, null); //清除cookie
1 请登录后投票
   发表时间:2009-11-20  

jQuery版的

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

 事实上这个版本可以不用jQuery来写的,因为代码里面只用了

jQuery.trim

这一个方法,完全可以写成独立的对象,用法形式上有jQuery方法的风格

2 请登录后投票
   发表时间:2009-11-24  
楼上对jquery的参数机制很熟啊 ,研究过jQuery源码吧
0 请登录后投票
   发表时间:2009-11-24  
我自己写的,为什么你这种帖子也能上首页,我自己写的框架就被评为新手帖??

cookie.js
xu.pkg('xu.cookie');
(function() {
	var Cookie = function(){		
		this.get = function (name) {
			var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
			if (arr != null) {
				return decodeURIComponent(arr[2]);
			}
			return null;
		};
		this.set = function (sName,sValue,objHours,sPath,sDomain,bSecure){
			var sCookie = sName + "=" + encodeURIComponent(sValue);
			if (objHours) {
				var date = new Date();
				var ms = objHours * 3600 * 1000;
				date.setTime(date.getTime() + ms);
				sCookie += ";expires=" + date.toGMTString();
			}
			if (sPath) {
				sCookie += ";path=" + sPath;
			}
			if (sDomain) {
				sCookie += ";domain=" + sDomain;
			}
			if (bSecure) {
				sCookie += ";secure";
			}
			document.cookie=sCookie;
		};		
		this.clear = function (sName,sPath,sDomain,bSecure){
			this.set(sName,'',0,sPath,sDomain,bSecure);
		} ;
	};
	xu.apply(xu.cookie,new Cookie());
})();

/* xu.cookie 功能测试*/
//xu.cookie.set('ua',xu.browser.ua);
//xu.cookie.set('chinese-char',"中文测试" + window.document.title);

//trace_obj("xu.cookie.get('ua')",xu.cookie.get('ua'));
//trace_obj("xu.cookie.get('chinese-char')",xu.cookie.get('chinese-char'));
//
//xu.cookie.clear('ua');
//xu.cookie.clear('chinese-char');




core.js如下:
/*
 * 编码规范: 包名小写,类名大写,函数名小写,对象定义名称大写
 * HTML标签小写,CSS名称小写,元素ID,name小写
 * 
 * 对js内置关键字做变量,在前面加上_标识符
 */

/**
 * 开发笔记:
 * 
 * -- IE6 hacker: * 
 * 	1. 元素ID不能以下划线开头
 *  2. COL, COLGROUP, FRAMESET, HTML, STYLE, TABLE, TBODY, TFOOT, THEAD, TITLE, TR
 *  	的很多属性只读,例如innerHTML,appendChild等等
 *  3. p 不能包容div、h1除了<br />等块级元素。否则报错
 *  4. a 不能包容div ;dt不能包容div,h
 */

var start_loaded_time = (new Date()).getTime();
// for old browsers
window.undefined = window.undefined;

// ------------------- 常用方法区域

//Camelcase 驼峰式风格 -- 第二个单词的首字母大写
String.prototype.getCamelcaseStyle = function(){	
	return this.replace(/-([a-z])/g, function(_0,_1){return _1.toUpperCase();});
};

/**
 * 创建元素
 * @param {} tagName
 * @return {}
 */
function $C(tagName) {
	return document.createElement(tagName);
}
/**
 * 返回带有指定标签名的对象的集合,注意集合不是数组
 * @param {} name
 * @return {}
 */
function $TagN(name) {
	return document.getElementsByTagName(name);
}

/**
 * 元素name属性名取 元素
 * @param {} name
 * @return {}
 */
function $N(name) {
	return document.getElementsByName(name);
}

/**
 * 元素ID属性名取 元素
 * @param {} name
 * @return {}
 */
function $ID(name) {
	return document.getElementById(name);
}

/**
 * 取指定节点下 具有CSS类名的元素数组
 * 摘自: js捷径教程
 * 
 * @param {} node
 * @param {} classname
 * @return {}
 */
function $clsN(node,classname) {
	var a = [] ;
	var re = new RegExp('(^| )' + classname + '( |$)');
	var els = node.getElementsByTagName('*');
	for(var i = 0 , j = els.length;i<j;i++){
		//排除 空白节点
		if (els[i] && (els[i].nodeType ==1 )&& (re.test(els[i].className) ) )
			a.push(els[i]);
	}
	return a ;
}

 var __proto = "prototype";
 var __class = "__class__";
 var __pkg = "__pkg__";
 var __superclass = "__superclass__";
 
 //顶级命名空间 -- xu
if (typeof xu == 'undefined') {
	xu = {
		version : '0.1' ,
		is_debug: true && 1 // 开启调试功能的变量
	};
}

/**
 * 将config对象中的属性全部复制给obj对象
 * 摘自: ext3.0
 * 
 * @param {} obj
 * @param {} config
 * @param {} defaults
 * @return {}
 */
xu.apply = function(obj, config, defaults){
    if(defaults){
        xu.apply(obj, defaults);
    }
    if(obj && config && typeof config == 'object'){
        for(var p in config){
            obj[p] = config[p];
        }
    }
    return obj;
};

xu.apply(xu,{
	/**
	 * 系统变量申明區域
	 * @type {}
	 */
	G_Var: {
		'PKGS': [] ,
	 	'APP_INF': {} ,
	 	'OBJECTS': {} ,
	 	'CLASS_PATH': {}
	} ,
	/**
	 * 定义包
	 * @param {} ns
	 * @return {}
	 */
	pkg: function(ns) {
		if (!ns || !ns.length) {
			return null;
		}
		var levels = ns.split(".");
		var nsobj = xu;
		for (var i = (levels[0] == "xu") ? 1 : 0; i < levels.length; ++i) {
			nsobj[levels[i]] = nsobj[levels[i]] || {};
			nsobj = nsobj[levels[i]];
		}
		xu['G_Var']['PKGS'].push(ns);
		return nsobj;
	} ,
	
	dump_pkg_list: function(){alert('依赖debug.js')} ,
	uid: function(){alert('依赖crypto.js')} ,
	
	/**
	 * 仅当obj对象不存在config对象中的属性时才将此属性复制给obj对象
	 * @param {} obj
	 * @param {} config
	 * @return {}
	 */
	applyIf : function(obj, config){
        if(obj){
            for(var p in config){
                if(xu.verify._null(obj[p])){
                    obj[p] = config[p];
                }
            }
        }
        return obj;
    } ,
    getAppInf: function(option){
    	if (option && !xu.verify._null(option) && xu['G_Var']['APP_INF'].hasOwnProperty(option)){
    		return xu['G_Var']['APP_INF'][option];
    	}
    	return null ;
    } ,
    
    setAppInf: function(option,value){
    	if (option && !xu.verify._null(option))
    		xu['G_Var']['APP_INF'][option] = value ;
    } ,
    map: function(obj,func){
    	if(obj){
    		obj = func(obj);
        }
        return obj;
    }
});

//xu.verify -- 变量类型验证
xu.pkg('xu.verify');
xu.apply(xu.verify,{
	_undef: function (v){return typeof v == "undefined";} ,
	_null: function (v){return v === null;} ,
	_arr: function (v){
	//	return xu.verify._obj(v) && v.constructor == Array;
		return Object[__proto].toString.call(v) === '[object Array]';
	} ,
	_str: function (v){return typeof v == "string";} ,
	_bool: function (v){return typeof v == "boolean";} ,
	_num: function (v){return typeof v == "number";} ,
	_int: function (v){return /^[01233456789]{1,}$/.test(v);} ,
	_func: function (v){return v && typeof v == "function";} ,
	_obj: function (v){return v && typeof v == "object";}
});

xu.pkg('xu._class') ;
(function() {
	xu.setAppInf('SYS_CLASS_NS','xu._class.sys');
	xu.setAppInf('USER_CLASS_NS','xu._class.user');
	
	xu.apply(xu._class,{
		create: function(pkg_n,class_n,p_class,class_impl,isOverride){
			
			if (xu.verify._null(class_n) || class_n === ""){ return null ;}
			
			try {
				var $t_class = eval(pkg_n + "." +class_n);
				if (this.exist($t_class)) {
					trace( "isExist: " + class_n + " Override:" + isOverride );
					if (!isOverride){	return null ;}
				}
			}
			catch(e){
				//如果出异常,说明该类没有定义
			}
					
			if (xu.verify._null(pkg_n) || pkg_n === ""){
				pkg_n = xu.getAppInf('USER_CLASS_NS') ;
			}
			$this_pkg = xu.pkg(pkg_n);	
			//定义父类,将子类的原型 指向父类
			if (xu.verify._null(p_class) || p_class === ""){
				p_class = xu._class.sys.XClass ;//这个类在匿名函数中创建
			}
			//定义类
			$t_class = $this_pkg[class_n] = function(){};
			$t_class['__instance_count__'] = 0 ;
			
			// 将子类的原型 指向父类,以此获取属性继承
			$t_class[__proto] = new p_class();
			var __superclass__ = ($t_class[__proto]['__str__']) ? 
				$t_class[__proto]['__str__'](true): 'Object' ;
				
			xu.apply($t_class[__proto],{
				'__pkg__': pkg_n ,			
				'__superclass__': __superclass__,
				'__class__': class_n
			});	
			
			if (!$t_class[__proto]['__str__']){
				$t_class[__proto]['__str__'] = function(isShort){
					if (!isShort)
						return "[class: " + this.__pkg__ + "." + this.__class__ + "]" ;
					return this.__pkg__ + "." + this.__class__ ;
				}			
			}
			
			if (xu.verify._obj(class_impl)){
				xu.apply($t_class[__proto],class_impl);
			} 
			return $t_class ;	
		} ,
		
		/**
		 * 验证类是否存在
		 * @param {String} Class
		 * @return {Boolean}
		 */
		exist: function(Class){
			if (xu.verify._func(Class))
				return true ;
			return false ;	
		}
		
		
	});
	//定义基类, 用于框架中所创建的类的基类.
	xu._class.create(xu.getAppInf('SYS_CLASS_NS'),'XClass',Object,{
		'desc': 'A System Base Class !'
	});
	
	Class = xu._class ;
})();


//定义时间对象
xu.pkg('xu.date');
xu.apply(xu.date,{
	start_loaded_time: start_loaded_time ,
	stop_loaded_time: -1 ,
	loaded_time: function(){
		this.stop_loaded_time = this.getTime();
		return this.stop_loaded_time - this.start_loaded_time ;
	} ,
	getTime: function(){return (new Date()).getTime();} 
});	 


ui.js
/**
 * UI Widget 包
 */
xu.pkg('xu.ui');

xu._class.create('xu.ui','Widget',null,{
	desc: 'Widget Base Class' ,options: {},
	instance: null ,error: false ,
	newInstance: function(Class){} ,
	config: function(options){
		xu.apply(this.options,options);
	} ,
	getWidget: function(){alert(this.__str__() + " getWidget() not implement");}
	,
	__err__: function(){		
		return this.__str__() + this.error;
	},
	destroy: function(){alert("销毁");}
});

//定义实例列表,用于缓存Widget对象 
xu.ui.Widget.instances = {} ;
/**
 * 快速构建Widget 对象的方法
 * 
 * @param String ref_n
 * @param {} options
 * @return xu.ui.Widget
 */
xu.ui.Widget.get = function(ref_n,options){
	if (xu.ui.Widget.instances.hasOwnProperty(ref_n))
		return xu.ui.Widget.instances[ref_n].getWidget();
	if (typeof options == 'undefined' || !xu.verify._obj(options)){
		var o_info = "'widget标识符',options: { type: Widget Class ,config: {类初始化参数} }" ;
		warn_msg('<br/>$widget('+ref_n+')初始化错误<br/>设置语法: ' + o_info);return null ;
	}
	var options = options || {} ;
	if (options['type'] && xu._class.exist(options['type']) && options['type'].prototype['getWidget']){
		var widget = new options['type']();
		widget.config(options['config']);
		var instance = widget.getWidget() ;
		if (instance){
			xu.ui.Widget.instances[ref_n] = widget ;
			return instance ;
		}
		warn_msg(widget.__err__());
		return null ;
	}	
};
$widget = xu.ui.Widget.get ;
$widget.destroy = function(ref_n){	 
	if (xu.ui.Widget.instances.hasOwnProperty(ref_n)){
		var w = xu.ui.Widget.instances[ref_n];
		if (w.destroy) w.destroy();
		delete xu.ui.Widget.instances[ref_n];
	}		
};


ui.widget.js
// widget 调用步骤: new , config , getWidget
/**
 * xu.ui.UCrenWidget -- Ucren Widget的封装器基类
 */
xu._class.create('xu.ui','UCrenWidget',xu.ui.Widget,{
	desc: 'Ucren Widget' ,xtype: null ,error: '依赖Ucren组件' ,
	newInstance: function(){
		try{
			var $t = eval(this.xtype);
			this.instance = new $t(this.options);
		}
		catch(e){}
		finally {
			return this.instance ;		
		}		
	} 
});

/**
 * xu.ui.UCrenWindow
 */
xu._class.create('xu.ui','UCrenWindow',xu.ui.UCrenWidget,{
	error: '依赖Ucren.FlashWindow' ,	xtype: 'Ucren.FlashWindow' ,
	options: {
		left: 170,top: 70,width: 400,height: 300,minWidth: 200,minHeight: 100,
		caption: '窗体',	resizeAble: true ,cloButton: true,cloAble: true	
	} ,
	getWidget: function(){
		if (this.instance) return this.instance ;
		return this.newInstance();
	} 
});

/**
 * xu.ui.HTMLWidget HTML 构件基类
 */
xu._class.create('xu.ui','HTMLWidget',xu.ui.Widget,{
	desc: 'HTML Widget Base Class',
	newInstance: function(){} ,
	config: function(options){
		xu.apply(this.options,options);
	} ,
	render: function(){alert(this.__str__() + " render() not implement");} 
	
});

/**
 * xu.ui.HTMLTable
 */
xu._class.create('xu.ui','HTMLTable',xu.ui.HTMLWidget,{
	desc: 'HTML Table' ,table:null,caption: null,thead: null ,tbody: null ,tfoot:null,
	options: {
		caption: null , columns: [] ,datas:{fields:[] ,records:[]} ,foots:[] ,
		css: {
			color: 'red'
		}
	} ,
	destroy: function(){
		if (!this.instance) return null ;
		with(this){
			instance.empty().remove();
			caption=null;tfoot=null;options = null ;thead=null;tbody=null;table=null;
		}
	},
	getWidget: function(){
		if (this.instance) return this ;
		this.instance = $eo.create('table');
		this.table = this.instance.ele;
		this.caption = this.table.createCaption();
		this.thead = this.table.createTHead();
		this.tbody = this.table.getElementsByTagName("tbody")[0] || this.table.appendChild($C("tbody"));
		this.tfoot = this.table.createTFoot();
		return this ;
	} ,
	render: function(ele){
		this.setCaption(this.options.caption);
		this.setTHead(this.options.columns);
		this.setTBody(this.options.datas);
		this.setTBody(this.options.foots);
		
		this.instance.css(this.options.css);
		this.instance.appendTo($eo(ele).ele);
		return this.instance.html() ;
	} ,	
	
	
	setCaption: function(v){
		if (v){
			this.caption.innerHTML = v ;
			this.options.caption = v ;
		}
	} ,	 
	setTHead: function(columns){
		if (xu.verify._arr(columns)){			
			var _tr = this.thead.insertRow(0);var _this = this ;			
			xu.array.each(columns,function(item,index){
				var _td = _tr.insertCell(index);
				_td.innerHTML = item.name ;
				if (item.width)
					xu.dom.css(_td,{width: item.width});
				if (item.dataIndex)
					xu.dom.attr(_td,{dataIndex: item.dataIndex});
				
			});
		}
	} ,
	setTBody: function(datas){
		if (xu.verify._obj(datas) && datas.fields && datas.records){
			var _this = this ;
			xu.array.each(datas.records,function(record,index){
				var _tr = _this.tbody.insertRow(index);
				xu.array.each(record,function(item,index){
					var _td = _tr.insertCell(index);
					_td.innerHTML = item ;
					
				});
			});
		}
	} ,
	setTFoot: function(foots){
		
	}
});
0 请登录后投票
   发表时间:2009-11-26  
cuixiping 写道
价值不高。

第一,不○○,现在大家好像比较重视这个。
第二,功能也不全面,cookie的有效时间应该做为参数传入,而不是写死在函数里面。

理论上至少应该是这样:

Cookie={
    set:function(params){...}
    ,get:function(params){...}
    ,remove:function(params){...}
}

但我不喜欢又是get又是set的,我喜欢合二为一,就像jquery那样,取值和设置值是同一个方法,只是参数不同。只传一个key就是取值,同时传了value就是设置。
所以要这样:
Cookie={
    item:function(params){...}
}
用的时候可以这样:
Cookie.item(key, value); //设置cookie
Cookie.item({key:key, value:value, expires:expires, domain:domain}); //设置cookie
var value = Cookie.item(key); //获取cookie
Cookie.item(key, null); //清除cookie




params 传个对象来好点.
0 请登录后投票
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics