Json string + Cookie + localstorage in JS

Json string + Cookie + localstorage in JS

1.Json string

Json is mainly used for front-end and back-end interaction. It is a data format that is more convenient to use than Xml.

1.1Json Syntax

Can be used to represent: objects, arrays, simple data types, etc.

  • {} represents an object, [] represents an array
  • The key and value are separated by ", and the key and key are separated by ". The attribute name must use the "
  • Try not to use NaN as the value. If there is no other attribute at the end of the attribute, do not keep it.

Conversion between Json and objects:

JSON string to object `JSON.parse(JSON string) will return the converted js object`
     Object to JSON string `JSON.stringify() is used to convert a value to a JSON string`


1.2 Examples

//Convert "string" data in object form to JSON object let s = `{"name":"onion","age":18}`;
 console.log(s) // string => {"name":"Onion","age":18}
 console.log(JSON.parse(s)); // //Object: object
//Convert "string" data in array form to JSON object let s = `[1,5,8,9]`;
 console.log(s); // string => [1,5,8,9]
 console.log(JSON.parse(s)); //Object: object
 -----------------------------------------------------------------------
 //Convert object to json string let s = {"name":"onion","age":18};
 console.log(JSON.stringify(s)); // string => {"name":"onion","age":18}
 // array to json string let s = [1,5,8,9];
   console.log(JSON.stringify(s)); // string => [1,5,8,9]

Notice:

  • During the conversion, the object's functions will be filtered out and will not be reflected in the results we print;
  • When deep copying, you can convert the object to a string first, and then convert it back to an object;
  • Json cannot store Data objects. Do not allow two properties with the same name to appear in the same object.
  • By default, the string output by JSON.stringify() will not contain spaces and indentation characters.

2. Cookies

Cookie record user information in the browser. When a page is opened in a server environment, we can obtain user operation information through settings. For example: remembering user passwords when logging in, information in the shopping cart on a personal Taobao account, etc. The validity period of a cookie can be session-level, long-term, or set.

2.1 How to use it?

  • We can create, delete, modify and read doucument.cookie .

Take a look at the example:

document.cookie = "name=onion";
document.cookie = "age=18";

The results are as follows:

We found the onions too spicy and I thought I'd try potatoes instead:

**document.cookie = "name=Onion";
document.cookie = "name=土豆";
document.cookie = "age=18";


The results are as follows:

After eating potatoes for a while, I found that potatoes are not good and I don’t want them anymore. What should I do? So how do we delete it? In fact, careful friends have discovered that there is a session level where we can set a validity period, and this date is the expiration date, using the expires keyword.

 document.cookie = "name=土豆;expires="+new Date('2021/11/25 03:58:20');


3. Local storage

H5 adds loclstorage and sessionStorage for local storage. The validity period localstorage is permanent, and the validity period of sessionStorage is at the session level. Here we focus on loclstorage .

3.1 Basic Use

Use window.localstorage to operate localstorage (window can be omitted)

//Add setItem
localStorage.setItem("name","onion");
//GetItem
localStorage.getItem("name","onion");
//deleteremoveItem("key-value pair")
localStorage.removeItem("name");
// Clear
localStorage.clear();


3.2 Example (Remember username and password)

Requirement: After the user enters the username and password, click the checkbox to remember the username and password so that they do not need to enter them again the next time they log in.

Username: <input type="text" id="username">
  <br>
  Password: <input type="password" id="pwd">
  <br>
  <span style="font-size: 14px;">Remember username and password:</span> 
  <input type="checkbox" id="remember">

    // Checkbox const remember = document.getElementById('remember');
    //Username const username = document.getElementById('username');
    //Password const pwd = document.getElementById('pwd');
      
    remember.onclick = function(){
      if (remember.checked) {
        //Select and store the username and password in local storage.
        localStorage.setItem("username",username.value);
        localStorage.setItem("pwd",pwd.value);
      } else {
        // Change from selected to unselected, delete the username and password from local storage localStorage.removeItem("username");
        localStorage.removeItem("pwd");
      }
      console.log();
    }
    //Each time you reopen the page, check if there is a value in the local storage if (localStorage.getItem("username")) {
      //If there is a value, write the value into the input box.
      username.value = localStorage.getItem("username")
      pwd.value = localStorage.getItem("pwd");
      //The checkbox is selected by default remember.checked = true;
    }

Effect: Once we enter the password and user name and click the checkbox, we don’t have to enter it again the next time we come in because the data is saved here↓

This is the end of this article about Json string + Cookie + localstorage in JS. For more relevant Json string + Cookie + localstorage content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Use of Local Storage and Session Storage in JavaScript
  • How to use SessionStorage and LocalStorage in Javascript
  • How to use localStorage in JavaScript
  • JavaScript local storage: use of localStorage, sessionStorage, and cookies
  • How to operate localstorage in js

<<:  Play mp3 or flash player code on the web page

>>:  Detailed explanation of the use of css-vars-ponyfill in IE environment (nextjs build)

Recommend

Example code for implementing an Upload component using Vue3

Table of contents General upload component develo...

JavaScript implements page scrolling animation

Table of contents Create a layout Add CSS styles ...

Code analysis of user variables in mysql query statements

In the previous article, we introduced the MySQL ...

JavaScript to achieve full or reverse selection effect in form

This article shares the specific code of JavaScri...

How to set up vscode remote connection to server docker container

Table of contents Pull the image Run the image (g...

Open the app on the h5 side in vue (determine whether it is Android or Apple)

1. Development environment vue+vant 2. Computer s...

A complete guide to the Docker command line (18 things you have to know)

Preface A Docker image consists of a Dockerfile a...

Implementation of nacos1.3.0 built with docker

1. Resume nacos database Database name nacos_conf...

Detailed explanation of slave_exec_mode parameter in MySQL

Today I accidentally saw the parameter slave_exec...

js to realize the mouse following game

This article shares the specific code of js to im...

CSS uses radial-gradient to implement coupon styles

This article will introduce how to use radial-gra...

Design Theory: Hierarchy in Design

<br />Original text: http://andymao.com/andy...

Install mysql5.7.17 using RPM under Linux

The installation method of MySQL5.7 rpm under Lin...

Summary of Linux ps and pstree command knowledge points

The ps command in Linux is the abbreviation of Pr...