Home Web Front-end JS Tutorial JavaScript encapsulation Cookie application interface_javascript skills

JavaScript encapsulation Cookie application interface_javascript skills

May 16, 2016 pm 03:46 PM
cookie javascript encapsulation

This article records some of the things I learned from reading the book while studying Cookie, deepens my memory and organizes and records them for future review.

Packaging function

Accessing cookies is a troublesome thing by default. Since cookies store information through strings, it is easy to convert the data type of the read information when performing assignment operations. Moreover, the string of cookie information itself is annoying, which is particularly inconvenient in web applications that often use cookie information. Therefore, you need to encapsulate a Cookie function yourself to provide development efficiency!

Define a function Cookie(). This function can write the specified Cookie information, delete the specified Cookie information, and read the Cookie value of the specified name. In addition, in this function, the validity period of the Cookie information can also be set. Valid paths, scopes, and security option settings. Complete code:

var Cookie = function(name, value, options) {
    // 如果第二个参数存在
    if (typeof value != 'undefined') {
      options = options || {};
      if (value === null) {
        // 设置失效时间
        options.expires = -1;
      }
      var expires = '';
      // 如果存在事件参数项,并且类型为 number,或者具体的时间,那么分别设置事件
      if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
        var date;
        if (typeof options.expires == 'number') {
          date = new Date();
          date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
        } else {
          date = options.expires;
        }
        expires = '; expires=' + date.toUTCString();
      }
      var path = options.path ? '; path=' + options.path : '', // 设置路径
        domain = options.domain ? '; domain=' + options.domain : '', // 设置域 
        secure = options.secure ? '; secure' : ''; // 设置安全措施,为 true 则直接设置,否则为空

      // 把所有字符串信息都存入数组,然后调用 join() 方法转换为字符串,并写入 Cookie 信息
      document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); 
    } else { // 如果第二个参数不存在
      var CookieValue = null;
      if (document.cookie && document.cookie != '') {
        var Cookie = document.cookie.split(';');
        for (var i = 0; i < Cookies.length; i++) {
          var Cookie = (Cookie[i] || "").replace( /^\s+|\s+$/g, "");
          if (Cookie.substring(0, name.length + 1) == (name + '=')) {
            CookieValue = decodeURIComponent(Cookie.substring(name.length + 1));
            break;
          }
        }
      }
      return CookieValue;
    }
  };

Copy after login

How to use

Write cookie information:

// 简单写入一条 Cookie 信息
cookie("user", "baidu");
// 写入一条 Cookie 信息,并且设置更多选项
cookie("user", "baidu", {
  expires: 10, // 有效期为 10 天
  path: "/", // 整个站点有效
  domain: "www.baidu.com", // 有效域名
  secure: true // 加密数据传输
});
Copy after login

2. Read cookie information:

cookie("user");
Copy after login

3. Delete cookie information:

cookie("user", null);
Copy after login

I will share with you a packaged code

//向cookie写入数据
function writeCookie(name, value, days) {
 // 定义有效日期(cookie的有效时间)
 var expires = "";

 // 为有效日期赋值
 if (days) {
  var date = new Date();
	//设置有效期(当前时间+时间段)
  date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));//时间段为毫秒数 
  expires = "; expires=" + date.toGMTString();
 }

 // 给cookie赋值 name, value和expiration date(有效期)
 document.cookie = name + "=" + value + expires + "; path=/";
}
//读取cookie数据
function readCookie(name) {
 var searchName = name + "=";
 var cookies = document.cookie.split(';');
 for(var i=0; i < cookies.length; i++) {
  var c = cookies[i];
  while (c.charAt(0) == ' ')
   c = c.substring(1, c.length);
  if (c.indexOf(searchName) == 0)
   return c.substring(searchName.length, c.length);
 }
 return null;
}
//清楚所有的cookie
function eraseCookie(name) {
 // 将时间设置成-1将清除存储在cookie中的数据
 writeCookie(name, "", -1);
}
Copy after login

Finally, if there are any errors or questions in the article, please point them out. Let’s encourage you all!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Where are cookies stored? Where are cookies stored? Dec 20, 2023 pm 03:07 PM

Cookies are usually stored in the cookie folder of the browser. Cookie files in the browser are usually stored in binary or SQLite format. If you open the cookie file directly, you may see some garbled or unreadable content, so it is best to use Use the cookie management interface provided by your browser to view and manage cookies.

Where are the cookies on your computer? Where are the cookies on your computer? Dec 22, 2023 pm 03:46 PM

Cookies on your computer are stored in specific locations on your browser, depending on the browser and operating system used: 1. Google Chrome, stored in C:\Users\YourUsername\AppData\Local\Google\Chrome\User Data\Default \Cookies etc.

Where are the mobile cookies? Where are the mobile cookies? Dec 22, 2023 pm 03:40 PM

Cookies on the mobile phone are stored in the browser application of the mobile device: 1. On iOS devices, Cookies are stored in Settings -> Safari -> Advanced -> Website Data of the Safari browser; 2. On Android devices, Cookies Stored in Settings -> Site settings -> Cookies of Chrome browser, etc.

TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year Apr 17, 2024 pm 08:00 PM

According to news from this site on April 17, TrendForce recently released a report, believing that demand for Nvidia's new Blackwell platform products is bullish, and is expected to drive TSMC's total CoWoS packaging production capacity to increase by more than 150% in 2024. NVIDIA Blackwell's new platform products include B-series GPUs and GB200 accelerator cards integrating NVIDIA's own GraceArm CPU. TrendForce confirms that the supply chain is currently very optimistic about GB200. It is estimated that shipments in 2025 are expected to exceed one million units, accounting for 40-50% of Nvidia's high-end GPUs. Nvidia plans to deliver products such as GB200 and B100 in the second half of the year, but upstream wafer packaging must further adopt more complex products.

Detailed explanation of where browser cookies are stored Detailed explanation of where browser cookies are stored Jan 19, 2024 am 09:15 AM

With the popularity of the Internet, we use browsers to surf the Internet have become a way of life. In the daily use of browsers, we often encounter situations where we need to enter account passwords, such as online shopping, social networking, emails, etc. This information needs to be recorded by the browser so that it does not need to be entered again the next time you visit. This is when cookies come in handy. What are cookies? Cookie refers to a small data file sent by the server to the user's browser and stored locally. It contains user behavior of some websites.

AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix Jul 18, 2024 am 02:04 AM

This website reported on July 9 that the AMD Zen5 architecture "Strix" series processors will have two packaging solutions. The smaller StrixPoint will use the FP8 package, while the StrixHalo will use the FP11 package. Source: videocardz source @Olrak29_ The latest revelation is that StrixHalo’s FP11 package size is 37.5mm*45mm (1687 square millimeters), which is the same as the LGA-1700 package size of Intel’s AlderLake and RaptorLake CPUs. AMD’s latest Phoenix APU uses an FP8 packaging solution with a size of 25*40mm, which means that StrixHalo’s F

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Frequently Asked Questions and Solutions about Cookie Settings Frequently Asked Questions and Solutions about Cookie Settings Jan 19, 2024 am 09:08 AM

Common problems and solutions for cookie settings, specific code examples are required. With the development of the Internet, cookies, as one of the most common conventional technologies, have been widely used in websites and applications. Cookie, simply put, is a data file stored on the user's computer that can be used to store the user's information on the website, including login name, shopping cart contents, website preferences, etc. Cookies are an essential tool for developers, but at the same time, cookie settings are often encountered

See all articles