This article describes the JS simple settings and the use of cookies method. Share to everyone for your reference, specific as follows:
One, JS set the use of cookies
PHP can set cookies, using JS to set cookies What is the benefit? In the front of the operation, sometimes to pass many parameters, this time, we can splice these parameters to the URL after the transfer value, there is receiving parameters, but this is very troublesome, if the data into the cookie, the developer's development efficiency, I think will be higher, to Taobao for example, He has a classification, level two classification, three, four, we look for goods, may involve a lot of conditions, if these conditions are put into the cookie, I feel more convenient, do not know Taobao is not like this. Taobao's URL is added secret, and very long, it may be the root in the back of the URL. Crap not to say a little more to see a small example.
Second, JS example
Gets
the cookie function GetCookie (name) {
var Nameeq = name + ' = ';
var ca = Document.cookie.split (';'); Split cookies into groups for
(Var i=0;i < ca.length;i++) {
var c = ca[i];//Get String while
(C.charat (0) = = ") {//Judge if String has No leading space
C = c.substring (1,c.length);//If any, start with the second bit
}
if (C.indexof (Nameeq) = 0) {//If the name
we want is included Return unescape (c.substring (nameeq.length,c.length)); Decode and intercept our value
}
} return
false;
Clears the cookie
function ClearCookie (name) {
Setcookie (name, "",-1);
}
Set cookie
function Setcookie (name, value, seconds) {
seconds = seconds | | 0;//seconds has a value directly assigned, not 0, this root PHP is not the same.
var expires = "";
if (seconds!= 0) {//Set cookie lifetime
var date = new Date ();
Date.settime (Date.gettime () + (seconds*1000));
expires = "; Expires= "+date.togmtstring ();
}
Document.cookie = name+ "=" +escape (value) +expires+ "; path=/"; Turn code and assign value
}
Call the above method:
Setcookie ("Test", "Tank", 1800); Set the value of the cookie, the lifetime is half an hour
alert (getcookie (' Test '));//Get the value of the cookie, display the tank
clearcookie ("test");//delete the value of the cookie
Alert (GetCookie (' Test '));//test the corresponding cookie value is null and is displayed as false. Is the value of the GetCookie last return.
I hope this article will help you with JavaScript programming.