Jump to content
php.lv forumi
  • 0

Cookies


EdgarsK

Question

Ticu, daudziem būs noderīgi.

 

Lūk kods kā apstrādāt (pievienot , lasīt , dzēst) cepumiņus ar Js palīdzību.

 

function createCookie(name,value,days) {
if (days) {
	var date = new Date();
	date.setTime(date.getTime()+(days*24*60*60*1000));
	var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
	var c = ca[i];
	while (c.charAt(0)==' ') c = c.substring(1,c.length);
	if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}

Edited by EdgarsA
Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

Pats sev uzrakstīju šādu risinājumu. OOP FTW.

var cookie: {
/**
 * Atgriež cepumu ar norādīto nosaukumu.
 *
 * @param	string	name	cookie name
 * @param	mixed	def		optional default value, false by default
 */
get: function(name, def){
	var r = new RegExp(name+"=([^;]+)", "i");
	var m = document.cookie.match(r);
	return m ? m[1] : (typeof def == "undefined" ? false : def);
},
/**
 * Uzseto cepumu.
 *
 * @param	string	name	cookie name
 * @param	string	value	cookie value
 * @param	int		expire	optional expiration time (seconds from now), 0 by default (end of session)
 * @param	string	path	optional cookie path, current by default
 */
set: function(name, value, expire, path){
	var c = name+"="+value;
	if(typeof expire != "undefined"){
		var exd = new Date();
		exd.setDate(exd.getDate()+expire);
		c+= ";expires="+exd.toUTCString();
	}
	if(typeof path != "undefined") c+= ";path="+path;
	document.cookie = c;
}
};

cookie.set('aaa', '123');
cookie.get('aaa'); // string 123
cookie.get('bbb'); // bool false
cookie.get('ccc', '321'); // string 321
cookie.set('aaa', '', -1);
cookie.get('aaa'); // bool false

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...