JavaScript operates on an cookie class instance
- 2020-05-24 05:10:42
- OfStack
This article illustrates the JavaScript operation cookie class as an example. Share with you for your reference. The details are as follows:
Usage:
1. Set the cookie
var cookie = new JSCookie();
// General Settings
cookie .SetCookie("key1","val1");
// The expiration time is 1 years
var expire_time = new Date();
expire_time.setFullYear(expire_time.getFullYear() + 1);
cookie .SetCookie("key2","val2",expire_time);
// Set field and path with expiration time
cookie .SetCookie("key3","val3",expire_time,".cnblogs.com","/");
// Set the tape key cookie, The subkeys are k1,k2,k3
cookie .SetCookie("key4","k1=1&k2=2&k3=3");
2. Read the cookie
// Easy access to
cookie .GetCookie("key1");
cookie .GetCookie("key2");
cookie .GetCookie("key3");
cookie .GetCookie("key4");
// To obtain key4 A child of the key k1 value
cookie .GetChild("key4","k1");
3. Delete
cookie .Expire("key1");
cookie .Expire("key2");
cookie .Expire("key3");
cookie .Expire("key4");
Example:
<script type="text/javascript">
String.prototype.Trim = function()
{
return this.replace(/^\s+/g,"").replace(/\s+$/g,"");
}
function JSCookie()
{
this.GetCookie = function(key)
{
var cookie = document.cookie;
var cookieArray = cookie.split(';');
var getvalue = "";
for(var i = 0;i<cookieArray.length;i++)
{
if(cookieArray[i].Trim().substr(0,key.length) == key)
{
getvalue = cookieArray[i].Trim().substr(key.length + 1);
break;
}
}
return getvalue;
};
this.GetChild = function(cookiekey,childkey)
{
var child = this.GetCookie(cookiekey);
var childs = child.split('&');
var getvalue = "";
for(var i = 0;i < childs.length;i++)
{
if(childs[i].Trim().substr(0,childkey.length) == childkey)
{
getvalue = childs[i].Trim().substr(childkey.length + 1);
break;
}
}
return getvalue;
};
this.SetCookie = function(key,value,expire,domain,path)
{
var cookie = "";
if(key != null && value != null)
cookie += key + "=" + value + ";";
if(expire != null)
cookie += "expires=" + expire.toGMTString() + ";";
if(domain != null)
cookie += "domain=" + domain + ";";
if(path != null)
cookie += "path=" + path + ";";
document.cookie = cookie;
};
this.Expire = function(key)
{
expire_time = new Date();
expire_time.setFullYear(expire_time.getFullYear() - 1);
var cookie = " " + key + "=e;expires=" + expire_time + ";"
document.cookie = cookie;
}
}
</script>
That's it.
I hope this article has been helpful to your javascript programming.