Home  >  Article  >  Web Front-end  >  Explore practical application scenarios of using sessionStorage to store data

Explore practical application scenarios of using sessionStorage to store data

PHPz
PHPzOriginal
2024-01-13 09:43:06685browse

Explore practical application scenarios of using sessionStorage to store data

Exploration of practical scenarios using sessionStrage to store data

Introduction

As web applications become more and more complex, we often need to store data on different pages or Save some data when refreshing the page. This requirement can be easily achieved using the browser's sessionStorage. This article explores several common scenarios and provides specific code examples. I hope it can help readers better understand and apply sessionStorage.

1. Form data storage

In many applications, we often need to save the form data being filled in by the user to prevent data loss caused by user misoperation or page refresh. This functionality can be easily achieved using sessionStorage.

The following is a simple example: Suppose we have a form containing two input boxes: name and age. When the user fills out the form, we save the data to sessionStorage. The code is as follows:

// 获取表单元素
const form = document.querySelector('#myForm');
const nameInput = form.querySelector('#name');
const ageInput = form.querySelector('#age');

// 监听表单提交事件
form.addEventListener('submit', function (e) {
  e.preventDefault();
  
  // 获取用户输入的数据
  const name = nameInput.value;
  const age = ageInput.value;
  
  // 存储数据到 sessionStorage
  sessionStorage.setItem('name', name);
  sessionStorage.setItem('age', age);
});

After another page or refreshing the current page, we can use the following code to restore the previously saved form data:

// 获取保存的数据
const savedName = sessionStorage.getItem('name');
const savedAge = sessionStorage.getItem('age');

// 恢复数据到表单中
nameInput.value = savedName;
ageInput.value = savedAge;

2. Shopping cart data storage

Another common application scenario is to save the user's shopping cart data. When a user purchases a product on the website, we can save the product information to sessionStorage so that the user can see the previously selected product when he or she goes to the checkout page.

The following is a simple example: suppose the user can select an item in the item list and add the selected item to the shopping cart. Every time the user selects a product, we save the product information to sessionStorage. The code is as follows:

// 获取商品列表元素
const products = document.querySelectorAll('.product');

// 监听商品选择事件
products.forEach(function (product) {
  const btn = product.querySelector('button');
  btn.addEventListener('click', function () {
    // 获取商品信息
    const name = product.querySelector('.name').textContent;
    const price = product.querySelector('.price').textContent;
    
    // 获取购物车数据(如果有)
    const cart = JSON.parse(sessionStorage.getItem('cart')) || [];

    // 添加选择的商品到购物车
    cart.push({ name, price });

    // 更新购物车数据
    sessionStorage.setItem('cart', JSON.stringify(cart));
  });
});

On the checkout page or after refreshing the current page, we can use the following code to obtain the shopping cart data and display it to the user:

// 获取购物车数据
const cart = JSON.parse(sessionStorage.getItem('cart'));

// 显示购物车数据
cart.forEach(function (item) {
  // 创建 DOM 元素,并显示数据
});

3. User login status storage

The last scenario is to save the user's login status. For example, after the user enters their username and password on the login page, we can save the login status to sessionStorage so that the user remains logged in while browsing other pages of the website.

The following is a simple example: assuming that after the user successfully logs in on the login page, we save the login status to sessionStorage. The code is as follows:

// 监听登录表单提交事件
const form = document.querySelector('#loginForm');
form.addEventListener('submit', function (e) {
  e.preventDefault();
  
  // 获取用户输入的用户名和密码
  const username = form.querySelector('#username').value;
  const password = form.querySelector('#password').value;
  
  // 模拟登录验证
  const isLoggedIn = checkLogin(username, password);
  
  // 保存登录状态到 sessionStorage
  sessionStorage.setItem('isLoggedIn', isLoggedIn);
});

In other pages, we can use the following code to check the user’s login status:

// 检查登录状态
const isLoggedIn = sessionStorage.getItem('isLoggedIn');

if (isLoggedIn) {
  // 用户已登录,执行相应的操作
} else {
  // 用户未登录,执行相应的操作
}

Conclusion

Through the code examples of the above specific scenarios, We can see the practical application of sessionStorage in Web development. It can easily help us store and restore data, making the user experience more friendly. Of course, sessionStorage also has some limitations. For example, the data is only valid until the current browser window is closed, and the sessionStorage data of each page is independent of each other. But in many scenarios, sessionStorage is still a very convenient and practical tool.

The above is the detailed content of Explore practical application scenarios of using sessionStorage to store data. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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