1, JavaScript Cookie in the user information storing web pages.

Summary: the cookie each browser has a number of limitations. Each browser, each cookie has a path a path to a web page request access.

------------------------------------------------------------------------------------------------

1. What is a cookie?

2, through JavaScript: create / read / change / delete cookie

3, Cookie string

4, JavaScript Cookie Example: Set / Get function / cookie is detected

-----------------------------------------------------------------------------------------------

What is a cookie? (Prerequisite: Web page requires the user to log in to request access)

Cookie is a small data text file stored on your computer.

When the web server sends the page to the browser, the connection is closed, the server will forget all users.

Cookie is to solve the "how to remember user information" invented:

  • When a user visits a page, his name can be stored in a cookie.
  • The next time the user visits the page, cookie "remembers" his name.

Cookie is stored in name-value pairs, such as:

username = Bill Gates

From the server when the browser requests a web page , the belonging page cookie added to the request in. So the server to obtain the necessary data to "remember" the user's information.

If the browser is closed local cookie support, the following examples are not working.

Create a cookie with JavaScript

JavaScript can be used document.cookie  create a property, read, delete cookie. 

Create a cookie:

document.cookie = "username=Bill Gates";

By default, when the browser is closed will delete cookie.

Expiration date may be added ( Expires = UTC time ):

document.cookie = "username=John Doe; expires=Sun, 31 Dec 2017 12:00:00 UTC";

By default, cookie belongs to the current page.

By  path = parameter , you can tell the browser what belongs cookie path.

document.cookie = "username=Bill Gates; expires=Sun, 31 Dec 2017 12:00:00 UTC; path=/";

Read cookie through JavaScript

Read cookie:

var x = document.cookie;

document.cookie will a string returns in all Cookie , for example: cookie1 = value; cookie2 = value ; cookie3 = value;

JavaScript by changing the cookie

Like a cookie as you create change it:

document.cookie = "username=Steve Jobs; expires=Sun, 31 Dec 2017 12:00:00 UTC; path=/";

The old cookie is overwritten.

Delete the cookie through JavaScript

Delete the cookie is very simple.

When you delete a cookie you do not have to specify the value of the cookie:

Directly  expires = parameter set date in the past to:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

Cookie path should be defined to ensure proper deletion of the cookie. Do not specify a path, some browsers will not let you delete the cookie.

Cookie string

Want to find a specified value of the cookie, you must write a JavaScript function to search for cookie cookie value string.

JavaScript Cookie examples

In the following example, we will create a cookie to store the name of the visitor .

Visitors first time landing pages, he will be asked to fill in the names. Then the name is stored in a cookie.

Next visitor reaches the same page, he will receive a welcome message.

For example, we will create three JavaScript functions:

  1. Set cookie value function
  2. Gets the value of the cookie function
  3. Function checks the value of the cookie

Set the cookie function

Create a function, the visitor's name is stored in the cookie variable in:

/ * 
 * CNAME: cookie name 
 * cvalue: cookie value 
 * exdays: the number of days overdue cookie 
 * by (cookie name, cookie value and the expiration string) added the function to set the cookie. 
* / 
Function the setCookie (CNAME, cValue, exdays) {
     var D = new new a Date (); 
    d.setTime (d.getTime () + (exdays * 24 * 60 * 60 * 1000 ));
     var Expires = "Expires =" + d.toUTCString (); 
    the document.cookie = CNAME + "=" + cValue + ";" Expires + + "; path = /" ;   
}

Obtain the cookie function

Create a function that returns the specified cookie value:

/ * 
 * The cookie as a parameter (cname). 
 * Create a variable (name) with the text you want to search (CNAME "="). 
 * Decode the cookie string, cookie processing with special characters, such as "$." 
 * The split document.cookie to ca named semicolon (decodedCookie.split ( ';')) in the array. 
 * Ca traverse the array (i = 0; i <ca.length ; i ++), and then reads out each value c = ca [i]. 
 * If you find a cookie (c.indexOf (name) == 0 ), the value of the cookie (c.substring (name.length, c.length) returns. * 
 If the cookie is not found, it returns "." 
* / 
Function the getCookie (CNAME) {
     var name = CNAME + "=" ;
     var decodedCookie = decodeURIComponent (the document.cookie);
     var CA = decodedCookie.split ( ';');     // the cookie into groups 
    for ( var I = 0; i <ca.length;) {   
         Var C = CA [I];   // to take the string 
        the while (c.charAt (0) == '') {   // Returns the character at the specified position determining bit string has no && leading spaces 
            c = c. the substring (1);   // taken after 1 && all remaining available as a string, a second bit taken from the beginning 
         }
          IF (c.indexOf (name) == 0) { // retrieve character string in the return the position of the first occurrence of 
            return c.substring (name.length, c.length); // extract a string intermediary between two specified index characters (i.e., "=" and ";" between the characters) . 
         } 
     } 
    Return "" ; 
}
/ * 
        The while (c.charAt (0) == '') { 
            C = c.substring (. 1);   
         } 
 * /   
// can be alternatively following code 
 var C = CA [I] .trim ();    // removed trailing spaces (c = ca [i] .trim ()).

Cookie detection function

/ * 
 * Create a function to check whether the cookie settings. 
 * If you have set a cookie, will display a greeting. 
 * If you do not set a cookie, will display a prompt box appears asking the user's name, and stores the user name cookie 365 days by calling setCookie function: 
* / 
function checkCookie () {
     var username = getCookie ( "username" );
     IF (username ! = "" ) { 
        Alert ( "available for purchase Again" + username); 
    } the else { 
        username = prompt ( "Please Enter your name:", "" );
         IF !! (username = "" && username = null ) { 
            the setCookie ( "username", username, 365 );

Combined

<!DOCTYPE html>
<html>
<head>
<script>
function setCookie(cname,cvalue,exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  var expires = "expires=" + d.toGMTString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for(var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

function checkCookie() {
  var user=getCookie("username");
  if (user != "") {
    alert("再次欢迎您," + user);
  } else {
     user = prompt("请输入姓名:","");
     if (user != "" && user != null) {
       setCookie("username", user, 30);
     }
  }
}
</script>
</head>

<body onload="checkCookie()"></body>

</html>

 

Guess you like

Origin www.cnblogs.com/Strugglinggirl/p/10981488.html