Home > Web Front-end > JS Tutorial > JS operation cookies include (reading, adding and deleting)_javascript skills

JS operation cookies include (reading, adding and deleting)_javascript skills

WBOY
Release: 2016-05-16 17:45:23
Original
1224 people have browsed it

I have always simply used js to implement some cookie operations. Today I have sorted out js's use of cookie operating systems, including: js reading cookies, js adding cookies, and js deleting cookies. Examples are as follows:

Copy code The code is as follows:





Cookie processing function exercise (written by me, not what I thought: improving object orientation)
< script language="JavaScript" type="text/javascript">
function addCookie(objName,objValue,objHours){//Add cookie
var str = objName "=" escape(objValue);
if(objHours > 0){//When it is 0, the expiration time is not set, and the cookie disappears automatically when the browser is closed
var date = new Date();
var ms = objHours*3600*1000;
date.setTime(date.getTime() ms);
str = "; expires=" date.toGMTString();
}
document.cookie = str;
alert("Add cookie successful");
}
function getCookie(objName){//Get the value of the cookie with 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){//In order to delete the 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 Take out all cookie strings
function allCookie(){//Read all saved cookie strings
var str = document.cookie;
if(str == ""){
str = "No cookies saved";
}
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 successfully");
}

//Add cookie
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 is days
str =";expires=" date.toGMTString();
}
if(path!=""){
str =";path=" path;//Specify the directory where cookies can be accessed
}
if(domain!=""){
str =";domain=" domain;//Specify the domain that can access cookies
}
document.cookie=str;
}
//Get cookies
function getCookie(name){
var str=document.cookie.split(";")
for(var i=0;ivar str2=str[i].split("=" );
if(str2[0]==name)return unescape(str2[1]);
}
}
//Delete cookie
function delCookie(name){
var date=new Date();
date.setTime(date.getTime()-10000);
document.cookie=name ”=n;expire=” date.toGMTString();

[Personally, I think the following is better! ]
Of course we have to introduce the four attributes of cookies. These attributes are appended to the string value in the following format:
name=[; expires=][; domain=][; path=][ ; secure]
name=[; expires=][; domain=][; path=][; secure]
, , and should be replaced with the corresponding values. GMT format should be used. You can use the .toGMTString() method of the date class Date in Javascript scripting language to obtain the date value in GMT format. Square brackets indicate that this item is optional. For example, the square brackets around [; secure] mean that if you want to set the cookie to be secure, you need to add "; secure" to the end of the cookie string value. If "; secure" is not added to the end of the cookie string, then the cookie is not secure. Do not add angle brackets <> and square brackets [] to cookies (unless they are the content of some value). When setting attributes, there is no limit to attributes and can be set in any order.

The following is an example. In this example, the cookie "username" is set to expire after 15 minutes, can be accessed by all directories on the server, and can be accessed by all servers in the "mydomain.com" domain. Access, the security status is safe.
Copy code The code is as follows:

// The constructor of Date() is set in milliseconds Unit
// The .getTime() method returns the time in milliseconds
// So to set the 15-minute expiration, multiply 60000 milliseconds 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 to read a specific cookie value. [Get the cookie object with the specified name! ]
function getCookie(cookie_name)
{
var allcookies = document.cookie;
var cookie_pos = allcookies.indexOf(cookie_name);
// If the index is found, it means that the cookie exists ,
// Otherwise, it means it does not exist.
if (cookie_pos != -1)
{
// Put cookie_pos at the beginning of the value, just add 1 to the value.
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 is it useless if I set the cookie expiration time if it is automatically cleared when it is closed?
Let’s study how JSP manipulates cookies?
Cookie concept:
The format of a cookie is actually a piece of plain text information, which is sent by the server to the client along with the web page, and is saved in The specified directory in the client's hard drive. Everyone says that cookies can cause serious security threats, but this is not the case. When the server reads the cookie, it can only read information related to the server. Moreover, the browser Generally, only 300 cookies are allowed to be stored, and each site can store up to 20 cookies. Moreover, the size of each cookie is now 4K, which does not take up much space at all. Moreover, cookies are time-sensitive. For example, if the cookie survival is set If the time is 1 minute, the cookie will be deleted by the browser after one minute
Cookie version:
There are currently two versions :
Version 0: formulated by Netscape. It is also supported by almost all browsers. In order to maintain compatibility, Java currently only supports version 0. There must be no spaces, square brackets, parentheses, equal signs (=), commas, double quotes, or slashes in the cookie content. Question mark, @ symbol, colon, semicolon.
Version 1: Based on the RFC 2109 document. Many restrictions have been relaxed. All the characters restricted above can be used. But in order to maintain compatibility, these special characters should be avoided as much as possible.
Cookie operations in JSP : Type method name Method explanation
String getComment() Returns the comment in the cookie, if there is no comment, it will return a null value.
String getDomain() Returns the domain name applicable to the cookie in the cookie. Use the getDomain() method to indicate browsing The server returns the cookie to other servers in the same domain, and usually the cookie is only returned to the server with the exact same name as the server that sent it. Note that the domain name must start with a dot
int getMaxAge() returns the maximum time before the cookie expires, in seconds.
String getName() returns the name of the cookie.
String getPath() returns the path to which the cookie applies. If the path is not specified, the cookie will be returned to all pages in the directory where the current page is located and its subdirectories.
boolean getSecure() will return a true value if the browser sends cookies through a secure protocol, and a false value if the browser uses a standard protocol.
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) Sets the comment in the cookie
void setDomain(String pattern) Sets the domain name for the cookie in the cookie
void setMaxAge(int expiry) Sets the cookie expiration time in seconds.
void setPath(String uri) specifies the path for cookies.
void setSecure(boolean flag) Indicates the security protocol used by the browser, such as HTTPS or SSL.
void setValue(String newValue) sets a new value after the cookie is created.
void setVersion(int v) Set the protocol version that the cookie follows
A simple example
1. Write Cookie --- writecookie.jsp
---- -------------------------------------------------- -------
Copy code The code is as follows:

<%@ page contentType="text/html; charset=ISO8859_1" %>
<%
Cookie _cookie=new Cookie("user_delfancom", "delfan");
_cookie.setMaxAge(30*60); // Set the cookie survival time to 30 minutes
response.addCookie(_cookie); // Write to the client hard disk
out.print("Cookie writing completed");
%>

2. Read Cookie.jsp --- readcookie.jsp
------------------------------- ----------------------------------
Copy code The code is as follows:

<%
Cookie cookies[]=request.getCookies(); // Read and save all cookies in the applicable directory Into the cookies array
Cookie sCookie=null;
String sname=null;
String name=null;
if(cookies==null) // If there are no cookies
out.print ("none any cookie");
else
{
out.print(cookies.length "
");
for(int i=0;i{
sCookie=cookies[i];
sname=sCookie.getName();
name = sCookie.getValue();
out.println(sname "->" name "
");
}
}
%>

Two things to note Questions :
1. Cookie has a problem with the applicable path, that is, if writecookie.jsp and readcookie.jsp are to be placed in the agreed directory, if they are not in the same directory, the path needs to be set when writing, as The path where readcookie.jsp is located.
2. When reading the Cookie array, you need to determine whether it is empty (null). Many codes on the Internet do not write this point.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template