JS operation cookies include (read add and delete) _javascript tips

Source: Internet
Author: User
Tags time in milliseconds
has always been simple to JS to implement some of the cookies operation, today the cookie operating system of the collation of the first time, including: JS read cookie,js add cookie,js delete cookies, examples are as follows:
Copy Code code as follows:

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01//en" "HTTP://WWW.W3.ORG/TR/HTML4/STRICT.DTD" >
<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 "/>
<title>cookie processing functions (written for me, not what I think: improving object-oriented) </title>
<script language= "JavaScript" type= "Text/javascript" >
function Addcookie (objname,objvalue,objhours) {//Add cookies
var str = objname + "=" + Escape (ObjValue);
if (objhours > 0) {//0 does not set the expiration time, the cookie automatically disappears when the browser shuts down
var date = new Date ();
var ms = objhours*3600*1000;
Date.settime (Date.gettime () + ms);
str + = "; Expires= "+ date.togmtstring ();
}
Document.cookie = str;
Alert ("Add cookie succeeded");
}
function GetCookie (objname) {//Get the value of the cookie for the specified name
var arrstr = Document.cookie.split (";");
for (var i = 0;i < Arrstr.length;i + +) {
var temp = arrstr[i].split ("=");
if (temp[0] = = objname) return unescape (temp[1));
}
}
function Delcookie (name) {//To delete a cookie with the specified name, you can set its expiration time to a past time
var date = new Date ();
Date.settime (Date.gettime ()-10000);
Document.cookie = name + "=A;" Expires= "+ date.togmtstring ();
}
read out all the cookie word 筗 string up
function Allcookie () {//Read all saved cookie strings
var str = document.cookie;
if (str = = "") {
str = "Do not save any cookies";
}
alert (str);
}
function $ (m,n) {
return document.forms[m].elements[n].value;
}
function add_ () {
var cookie_name = $ ("MyForm", "cookie_name");
var Cookie_value = $ ("MyForm", "Cookie_value");
var cookie_expirehours = $ ("MyForm", "cookie_expireshours");
Addcookie (cookie_name,cookie_value,cookie_expirehours);
}
function get_ () {
var cookie_name = $ ("MyForm", "cookie_name");
var cookie_value = GetCookie (cookie_name);
alert (Cookie_value);
}
function Del_ () {
var cookie_name = $ ("MyForm", "cookie_name");
Delcookie (Cookie_name);
Alert ("Delete succeeded");
}
</script>
Add cookies
function Addcookie (name,value,expires,path,domain) {
var str=name+ "=" +escape (value);
if (expires!= "") {
var date=new date ();
Date.settime (Date.gettime () +expires*24*3600*1000);//expires Unit for day
str+= "; expires=" +date.togmtstring ();
}
if (path!= "") {
str+= ";p ath=" +path;//Specifies the directory where the cookie can be accessed
}
if (domain!= "") {
str+= ";d omain=" +domain;//Specify the domain that can access the cookie
}
DOCUMENT.COOKIE=STR;
}
Get cookies
function GetCookie (name) {
var str=document.cookie.split (";")
for (Var i=0;i<str.length;i++) {
var str2=str[i].split ("=");
if (str2[0]==name) return unescape (str2[1]);
}
}
Delete Cookies
function Delcookie (name) {
var date=new date ();
Date.settime (Date.gettime ()-10000);
Document.cookie=name+ "=n;expire=" +date.togmtstring ();

[The following speaking of the personal feel better Oh! ]
We also have to introduce four properties of cookies. These attributes are appended to the string value in the following format:
name=<value>[; expires=<date>][; domain=<domain>][; path=<path>][; Secure]
Name =< value >[; expires=< date >][; domain=< domain >][; path=< path >][; security]
<value&gt, <date&gt, <domain> and <path> should be replaced with corresponding values. <date> You should use the GMT format to get the date value of this GMT format using the date class dated. toGMTString () method of the JavaScript scripting language. The square brackets represent this item to be optional. For example, the square brackets on both sides of the [; secure] will need to be set to make the cookie safe; Secure "is appended to the cookie string value. If "; Secure "is not added to the cookie string, then this cookie is not secure. Do not add angle brackets <> and brackets [] to cookies (unless they are the contents of certain values). When you set properties, you do not have properties that can be set in any order.

The following is an example in which the cookie "username" is set to expire after 15 minutes and can be accessed by all directories on the server, and can be accessed by all servers in the "mydomain.com" domain, with a security state of security.
Copy Code code as follows:

The constructor for Date () is set in milliseconds
The. GetTime () method returns the time in milliseconds
So to set the 15-minute expiration, it takes 60000 milliseconds to multiply by 15 minutes
var expiration = new Date (new Date ()). GetTime () + 15 * 60000);
Document.cookie = "Username=" + Escape (Form.username.value) + "; expires = "
+ expiration.togmtstring () + "; Path= "+"/"+"; _
domain= "+" mydomain.com "+"; Secure ";
We define a function that is used to read a particular cookie value. [Cookie object with the specified name] Oh! ]
function GetCookie (cookie_name)
{
var allcookies = Document.cookie;
var cookie_pos = Allcookies.indexof (cookie_name);
If an index is found, it means that the cookie exists.
On the contrary, it means that it does not exist.
if (Cookie_pos!=-1)
{
Put the Cookie_pos at the beginning of the value, as long as the value plus 1.
Cookie_pos + = cookie_name.length + 1;
var cookie_end = Allcookies.indexof (";", Cookie_pos);
if (cookie_end = = 1)
{
Cookie_end = Allcookies.length;
}
var value = unescape (allcookies.substring (Cookie_pos, cookie_end));
}
return value;
}
Call function
var cookie_val = GetCookie ("username");

3. Why did I set the expiration time of the cookie if it was automatically emptied when it was closed?
To study JSP manipulation cookies?
Cookie Concept:
The cookie format is actually a piece of plain text information that is sent by the server along with the page to the client and saved in the directory specified on the client's hard disk. Everyone legends that cookies can pose a serious security threat or something, but that's not the case. When the server reads cookies, it can only read information about the server. Also, browsers typically allow only 300 cookies, each with a maximum of 20, and the size of each cookie is now 4K and will not occupy much space. Also, cookies are of a time-sensitive nature. For example, if a cookie is set to survive for 1 minutes, the cookie will be deleted by the browser in a minute.
Cookie version:
There are currently two versions:
Version 0: Made by Netscape and supported by almost all browsers. Java in order to maintain compatibility, currently only support to version 0, the contents of the cookie can not be space, square brackets, parentheses, equals number (=), commas, double quotes, slashes, question marks, @ symbol, colon, semicolon.
Version 1: Based on RFC 2109 documentation. Relaxed a lot of restrictions. The characters that are restricted above can be used. However, to maintain compatibility, you should try to avoid using these special characters.
Actions on cookies in JSP: Type method Name method explanation
String getcomment () returns a comment in the cookie, which returns a null value if there is no comment.
String GetDomain () returns the domain name that the cookie in the cookie applies to. Use the GetDomain () method to instruct the browser to return the cookie to another server in the same domain, and usually the cookie is returned only to servers that have exactly the same name as the server that sent it. Note that the domain name must start with a dot
int Getmaxage () returns the maximum time, in seconds, before the cookie expires.
String GetName () returns the name of the cookie
String GetPath () returns the path that the cookie applies to. If you do not specify a path, the cookie is returned to all pages in the directory and its subdirectories where the current page resides.
Boolean getsecure () if the browser sends cookies through a security protocol, returns a value of True if the browser uses the standard protocol to return a value of false.
String GetValue () returns the value of the cookie. The author will also introduce getvalue/setvalue in detail later.
int GetVersion () returns the protocol version that the cookie complies with.
void Setcomment (String purpose) set comment in cookie
void SetDomain (String pattern) sets the domain name that the cookie applies to in the cookie
void setmaxage (int expiry) Sets the cookie expiration time in seconds.
The void SetPath (String uri) specifies the path to which the cookie applies.
The Void SetSecure (Boolean flag) indicates the security protocol used by the browser, such as HTTPS or SSL.
Set a new value after the void SetValue (String newvalue) cookie is created.
void setversion (int v) Sets the protocol version that the cookie complies with
a simple example
1. Write Cookie---writecookie.jsp
-------------------------------------------------------------
Copy Code code as follows:

<%@ page contenttype= "text/html; Charset=iso8859_1 "%>
<%
Cookies _cookie=new Cookies ("user_delfancom", "Delfan");
_cookie.setmaxage (30*60); Set the cookie to live for 30 minutes
Response.addcookie (_cookie); Write to client hard disk
Out.print ("Write Cookie Complete");
%>

2. Read cookie.jsp---readcookie.jsp
-------------------------------------------------------------
Copy Code code as follows:

<%
Cookie cookies[]=request.getcookies (); Read all cookies in the applicable directory and deposit them in the cookie array
Cookie Scookie=null;
String Sname=null;
String Name=null;
if (cookies==null)//If there is no cookie
Out.print ("None any Cookie");
Else
{
Out.print (cookies.length + "<br>");
for (int i=0;i<cookies.length; i++)//Loops list all available cookies
{
Scookie=cookies[i];
Sname=scookie.getname ();
Name = Scookie.getvalue ();
Out.println (sname + "->" + name + "<br>");
}
}
%>

two issues to be aware of:
1. Cookies have a problem with the applicable path, that is, if the writecookie.jsp and readcookie.jsp to be placed in the consent directory, if not in the same directory, then write the path required to set, for the readcookie.jsp path.
2. Read the cookie array to determine whether it is empty (null), a lot of code on the web did not write this point.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.