js uses cookies to store text information - Chinese has been transcoded and decoded

JavaScript is a script that runs on the client, and cookies run on the client, so cookies can be used to store user information in web pages.

What are cookies?

A cookie is a small text file of data stored on your computer.

When the web server sends the web page to the browser, the connection is closed and the server forgets everything about the user.

Cookies were invented to solve "how to remember user information":

  • When a user visits a web page, his name can be stored in a cookie.

  • The next time the user visits the page, the cookie "remembers" his name.

For example: a global variable temp is defined, page A stores the user information name userName, the user information name userName has been assigned to the variable temp when page A is opened, and the variable temp will be reloaded when page B is opened, there is no To achieve the effect of storage, at this time, cookies are used to save the value of the variable.

Description of cookie storage size limit:
  • Only text can be stored.

  • The size of a single entry cannot exceed 4kb

  • The storage number generally does not exceed 50.

  • Cannot be read across domains.

  • Each cookie has a time limit, and the shortest validity period is at the session level (that is, the cookie is destroyed when the browser is closed).

Cookie read, delete, set:

cookie settings:

cname: set the cookie name, cvalue: set the value to be stored in the variable, exdays: set the storage date

Example of use: setCookie('XXX_userName', userName, 7), set the storage user name userName, and the storage validity period is 7 days.

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 + "=" + encodeURIComponent(cvalue) + "; " + expires;
};

The cookie reads:

Usage example: getCookie('XXX_userName'), read XXX_userName, stored value.

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

cookie deletion:

Example of use: deleteCookie('XXX_userName'), delete the value stored in the XXX_userName variable.

function deleteCookie(name) {
  var exp = new Date();
  exp.setTime(exp.getTime() - 1);
  var cval = getCookie(name);
  if (cval != null)
    document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
};

Guess you like

Origin blog.csdn.net/pinhmin/article/details/128712998