Hướng dẫn how to store data in javascript - cách lưu trữ dữ liệu trong javascript

Hướng dẫn how to store data in javascript - cách lưu trữ dữ liệu trong javascript

Show

Steve Alila

Đăng vào ngày 23 tháng 6 năm 2021 • Cập nhật vào ngày 27 tháng 9 năm 2021

Bạn có thể đã làm việc với cơ sở dữ liệu SQL như MySQL. Bạn đã tạo Frontend của trang web của mình, sau đó sử dụng ngôn ngữ lập trình để viết mã phụ trợ.

Bạn cũng có thể sử dụng JavaScript (Node.js.) để tạo một máy chủ để tương tác với cơ sở dữ liệu như PostgreSQL hoặc MongoDB.

Các thiết lập trên có thể dài và mệt mỏi cho một dự án đơn giản.

Giải pháp là lưu trữ dữ liệu trên máy khách, đọc, cập nhật và xóa nó bằng JavaScript thông qua:

  1. Lưu trữ tĩnh
  2. Lưu trữ cục bộ
  3. Phiên điều hành
  4. Lập chỉ mụcDB
  5. WebSQL
  6. Bánh quy
  7. API bộ đệm

Trong hướng dẫn này, chúng tôi sẽ khám phá ba cách điển hình để lưu trữ dữ liệu bằng JavaScript. Đó là:

  1. Lưu trữ tĩnh
  2. Lưu trữ cục bộ
  3. Phiên điều hành

Lập chỉ mụcDB

WebSQL

Bánh quy

  1. API bộ đệm
  2. Trong hướng dẫn này, chúng tôi sẽ khám phá ba cách điển hình để lưu trữ dữ liệu bằng JavaScript. Đó là:

Lưu trữ cục bộ

Sử dụng cơ sở dữ liệu trình duyệt

Chúng tôi sẽ tìm hiểu các đặc điểm của mỗi bộ lưu trữ, cách thức hoạt động và những nhược điểm của nó. Để nắm bắt các khái niệm, chúng tôi sẽ tạo một ứng dụng đơn giản.

Chúng tôi sẽ không sử dụng bất kỳ khung hoặc thư viện nào. Thay vào đó, chúng tôi sẽ tương tác với API DOM, API lưu trữ web và API

const todos = ['play piano', 'write some code', 'swim'];
7.

Sơ bộ

Bạn nên hiểu ES6 JavaScript vì chúng tôi sẽ viết mã bằng cú pháp ES6.

Nhận toàn bộ mã ứng dụng

const todos = ['play piano', 'write some code', 'swim'];
8 trên GitHub: https://github.com/alilasteve/todo

HTML

Chúng tôi liên kết tệp kiểu và tập lệnh bằng cách sử dụng thuộc tính

const todos = ['play piano', 'write some code', 'swim'];
9. Từ khóa trì hoãn có nghĩa là JavaScript của chúng tôi sẽ tải sau khi HTML tải xong.

const todosUl = document.querySelector('.todos');
const input = document.querySelector('#add');
const saveBtn = document.querySelector('#save');

Nhập chế độ FullScreenen EXIT Mode FullScreen

Cơ thể có window.addEventListener('DOMContentLoaded', () =>{ //show todos todos.forEach( todo => { let li = document.createElement('li'); li.textContent = todo; todosUl.appendChild(li); //delete todos li.addEventListener('dblclick', () => { todosUl.removeChild(li); }) }) const addTodos = e => { e.preventDefault(); let li = document.createElement('li'); li.textContent = input.value; todos.push(input.value); todosUl.appendChild(li); input.value = ''; } saveBtn.addEventListener('click', addTodos); }) 0 để gửi window.addEventListener('DOMContentLoaded', () =>{ //show todos todos.forEach( todo => { let li = document.createElement('li'); li.textContent = todo; todosUl.appendChild(li); //delete todos li.addEventListener('dblclick', () => { todosUl.removeChild(li); }) }) const addTodos = e => { e.preventDefault(); let li = document.createElement('li'); li.textContent = input.value; todos.push(input.value); todosUl.appendChild(li); input.value = ''; } saveBtn.addEventListener('click', addTodos); }) 1 để lưu trữ và window.addEventListener('DOMContentLoaded', () =>{ //show todos todos.forEach( todo => { let li = document.createElement('li'); li.textContent = todo; todosUl.appendChild(li); //delete todos li.addEventListener('dblclick', () => { todosUl.removeChild(li); }) }) const addTodos = e => { e.preventDefault(); let li = document.createElement('li'); li.textContent = input.value; todos.push(input.value); todosUl.appendChild(li); input.value = ''; } saveBtn.addEventListener('click', addTodos); }) 2 để hiển thị window.addEventListener('DOMContentLoaded', () =>{ //show todos todos.forEach( todo => { let li = document.createElement('li'); li.textContent = todo; todosUl.appendChild(li); //delete todos li.addEventListener('dblclick', () => { todosUl.removeChild(li); }) }) const addTodos = e => { e.preventDefault(); let li = document.createElement('li'); li.textContent = input.value; todos.push(input.value); todosUl.appendChild(li); input.value = ''; } saveBtn.addEventListener('click', addTodos); }) 1.

CSS

const todos = ['play piano', 'write some code', 'swim'];

Nhập chế độ FullScreenen EXIT Mode FullScreen

Chúng tôi chạy mã bên trong đối tượng cửa sổ với

localStorage.setItem('store_name', 'data_name'); 
//e.g
localStorage.setItem('name', 'Ahmed');

1 để đảm bảo
window.addEventListener('DOMContentLoaded', () =>{
        //show todos
    todos.forEach( todo => {
        let li = document.createElement('li');
        li.textContent =  todo;
        todosUl.appendChild(li);
        //delete todos
        li.addEventListener('dblclick', () => {
            todosUl.removeChild(li);
        })
    })

    const addTodos = e => {
    e.preventDefault();

    let li = document.createElement('li');
    li.textContent =  input.value;
    todos.push(input.value);
    todosUl.appendChild(li);
    input.value = '';
}
saveBtn.addEventListener('click', addTodos);
})
1 có sẵn để được hiển thị khi tải trang.

window.addEventListener('DOMContentLoaded', () =>{
        //show todos
    todos.forEach( todo => {
        let li = document.createElement('li');
        li.textContent =  todo;
        todosUl.appendChild(li);
        //delete todos
        li.addEventListener('dblclick', () => {
            todosUl.removeChild(li);
        })
    })

    const addTodos = e => {
    e.preventDefault();

    let li = document.createElement('li');
    li.textContent =  input.value;
    todos.push(input.value);
    todosUl.appendChild(li);
    input.value = '';
}
saveBtn.addEventListener('click', addTodos);
})

Nhập chế độ FullScreenen EXIT Mode FullScreen

Chúng tôi lặp qua

window.addEventListener('DOMContentLoaded', () =>{
        //show todos
    todos.forEach( todo => {
        let li = document.createElement('li');
        li.textContent =  todo;
        todosUl.appendChild(li);
        //delete todos
        li.addEventListener('dblclick', () => {
            todosUl.removeChild(li);
        })
    })

    const addTodos = e => {
    e.preventDefault();

    let li = document.createElement('li');
    li.textContent =  input.value;
    todos.push(input.value);
    todosUl.appendChild(li);
    input.value = '';
}
saveBtn.addEventListener('click', addTodos);
})
1, tạo một phần tử
localStorage.setItem('store_name', 'data_name'); 
//e.g
localStorage.setItem('name', 'Ahmed');

4 và hiển thị từng việc cần làm trên trang. Chúng ta có thể thêm
window.addEventListener('DOMContentLoaded', () =>{
        //show todos
    todos.forEach( todo => {
        let li = document.createElement('li');
        li.textContent =  todo;
        todosUl.appendChild(li);
        //delete todos
        li.addEventListener('dblclick', () => {
            todosUl.removeChild(li);
        })
    })

    const addTodos = e => {
    e.preventDefault();

    let li = document.createElement('li');
    li.textContent =  input.value;
    todos.push(input.value);
    todosUl.appendChild(li);
    input.value = '';
}
saveBtn.addEventListener('click', addTodos);
})
1 mới vào mảng bằng hàm
localStorage.setItem('store_name', 'data_name'); 
//e.g
localStorage.setItem('name', 'Ahmed');

6.

Nhược điểm

Chúng ta có thể thêm nhiều

window.addEventListener('DOMContentLoaded', () =>{
        //show todos
    todos.forEach( todo => {
        let li = document.createElement('li');
        li.textContent =  todo;
        todosUl.appendChild(li);
        //delete todos
        li.addEventListener('dblclick', () => {
            todosUl.removeChild(li);
        })
    })

    const addTodos = e => {
    e.preventDefault();

    let li = document.createElement('li');
    li.textContent =  input.value;
    todos.push(input.value);
    todosUl.appendChild(li);
    input.value = '';
}
saveBtn.addEventListener('click', addTodos);
})
1 vào mảng tĩnh, nhưng chúng biến mất trên trang làm mới. Đó là lý do tại sao chúng ta cần các cách khác để lưu trữ
window.addEventListener('DOMContentLoaded', () =>{
        //show todos
    todos.forEach( todo => {
        let li = document.createElement('li');
        li.textContent =  todo;
        todosUl.appendChild(li);
        //delete todos
        li.addEventListener('dblclick', () => {
            todosUl.removeChild(li);
        })
    })

    const addTodos = e => {
    e.preventDefault();

    let li = document.createElement('li');
    li.textContent =  input.value;
    todos.push(input.value);
    todosUl.appendChild(li);
    input.value = '';
}
saveBtn.addEventListener('click', addTodos);
})
1.

2. LocalStorage

JavaScript cho phép chúng tôi lưu trữ dữ liệu trong trình duyệt bằng API lưu trữ cục bộ. Tại đây, bạn có thể sử dụng

localStorage.setItem('store_name', 'data_name'); 
//e.g
localStorage.setItem('name', 'Ahmed');

9 và
localStorage.getItem('store_name');

//e.g
localStorage.getItem('name'); //Ahmed
//or 
localStorage // all stores

0. Các đối tượng cho phép chúng tôi lưu trữ dữ liệu (trong các cặp khóa/giá trị) và cập nhật nó từ lưu trữ của trình duyệt. Để xem dữ liệu, hãy mở trình duyệt của bạn. Kích chuột phải. Nhấp vào Kiểm tra => Ứng dụng => Lưu trữ.

Cả hai cách có cùng một cấu trúc. Sự khác biệt chính là

localStorage.setItem('store_name', 'data_name'); 
//e.g
localStorage.setItem('name', 'Ahmed');

9 cho phép chúng tôi lưu trữ dữ liệu miễn là chúng tôi muốn. Ngược lại,
localStorage.getItem('store_name');

//e.g
localStorage.getItem('name'); //Ahmed
//or 
localStorage // all stores

0 mất dữ liệu khi chúng tôi đóng cửa sổ hiện tại.

Làm thế nào nó hoạt động

Để lưu trữ dữ liệu, sử dụng hai tham số như được hiển thị.

localStorage.setItem('store_name', 'data_name'); 
//e.g
localStorage.setItem('name', 'Ahmed');

Nhập chế độ FullScreenen EXIT Mode FullScreen

Để kiểm tra mã, hãy xóa bảng điều khiển (Ctrl + L) và dán mã trên với bất kỳ tên cửa hàng nào bạn thích.

Bạn có thể truy xuất dữ liệu được lưu trữ bằng cách sử dụng

localStorage.getItem('store_name');

//e.g
localStorage.getItem('name'); //Ahmed
//or 
localStorage // all stores

3 như được hiển thị:

localStorage.getItem('store_name');

//e.g
localStorage.getItem('name'); //Ahmed
//or 
localStorage // all stores

Nhập chế độ FullScreenen EXIT Mode FullScreen

Bạn có thể xóa đối tượng lưu trữ

localStorage.removeItem('store_name');

//e.g
localStorage.removeItem('name');

Nhập chế độ FullScreenen EXIT Mode FullScreen

Hoặc xóa tất cả các đối tượng lưu trữ bằng cách sử dụng

localStorage.clear();

Nhập chế độ FullScreenen EXIT Mode FullScreen

localStorage.getItem('store_name');

//e.g
localStorage.getItem('name'); //Ahmed
//or 
localStorage // all stores

4 lưu trữ dữ liệu trong chuỗi. Trong ứng dụng TODO của chúng tôi, chúng tôi sử dụng nó như sau:

const getTodos = () => {
    let todos;
    if(localStorage.getItem('todos') === null){
        todos = [];
    }else {
        todos = JSON.parse(localStorage.getItem('todos'));
    }
    return todos;
}

Nhập chế độ FullScreenen EXIT Mode FullScreen

Trước tiên, chúng tôi tạo một biến,

localStorage.getItem('store_name');

//e.g
localStorage.getItem('name'); //Ahmed
//or 
localStorage // all stores

5 Tiếp theo, kiểm tra xem trình duyệt đã có một đối tượng lưu trữ có tên
localStorage.getItem('store_name');

//e.g
localStorage.getItem('name'); //Ahmed
//or 
localStorage // all stores

5 nếu nó không tồn tại, chúng tôi tạo một mảng trống. Nếu nó đã tồn tại, chúng ta có thể lấy nó sẵn sàng để được sử dụng trong các phần khác của mã.

Chúng tôi sử dụng

localStorage.getItem('store_name');

//e.g
localStorage.getItem('name'); //Ahmed
//or 
localStorage // all stores

7 để thay đổi
window.addEventListener('DOMContentLoaded', () =>{
        //show todos
    todos.forEach( todo => {
        let li = document.createElement('li');
        li.textContent =  todo;
        todosUl.appendChild(li);
        //delete todos
        li.addEventListener('dblclick', () => {
            todosUl.removeChild(li);
        })
    })

    const addTodos = e => {
    e.preventDefault();

    let li = document.createElement('li');
    li.textContent =  input.value;
    todos.push(input.value);
    todosUl.appendChild(li);
    input.value = '';
}
saveBtn.addEventListener('click', addTodos);
})
1 từ JSON sang chữ JavaScript thông thường. Sau đó, chúng tôi trả về đối tượng sẽ được sử dụng trong các phần khác của mã.

const saveTodos = inputData => {
    const todos = getTodos();
    todos.push(inputData);
    localStorage.setItem('todos', JSON.stringify(todos));
}

Nhập chế độ FullScreenen EXIT Mode FullScreen

Tạo

localStorage.getItem('store_name');

//e.g
localStorage.getItem('name'); //Ahmed
//or 
localStorage // all stores

9, với tham số
localStorage.removeItem('store_name');

//e.g
localStorage.removeItem('name');
0. Chúng tôi đẩy dữ liệu mới trong lưu trữ web. Và tạo lại đối tượng
localStorage.getItem('store_name');

//e.g
localStorage.getItem('name'); //Ahmed
//or 
localStorage // all stores

4. Chúng tôi
localStorage.removeItem('store_name');

//e.g
localStorage.removeItem('name');
2
window.addEventListener('DOMContentLoaded', () =>{
        //show todos
    todos.forEach( todo => {
        let li = document.createElement('li');
        li.textContent =  todo;
        todosUl.appendChild(li);
        //delete todos
        li.addEventListener('dblclick', () => {
            todosUl.removeChild(li);
        })
    })

    const addTodos = e => {
    e.preventDefault();

    let li = document.createElement('li');
    li.textContent =  input.value;
    todos.push(input.value);
    todosUl.appendChild(li);
    input.value = '';
}
saveBtn.addEventListener('click', addTodos);
})
1 trước khi lưu nó vì
localStorage.getItem('store_name');

//e.g
localStorage.getItem('name'); //Ahmed
//or 
localStorage // all stores

4 lưu trữ dữ liệu theo chuỗi. Sau đó chúng tôi tiến hành và nhận giá trị đầu vào từ hàm
localStorage.setItem('store_name', 'data_name'); 
//e.g
localStorage.setItem('name', 'Ahmed');

6 trong dòng

  saveTodos(input.value);

Nhập chế độ FullScreenen EXIT Mode FullScreen

như hình dưới đây:

const todos = ['play piano', 'write some code', 'swim'];
0

Nhập chế độ FullScreenen EXIT Mode FullScreen

Cuối cùng, chúng ta có thể xóa từng phần tử trong mảng

const todos = ['play piano', 'write some code', 'swim'];
1

Nhập chế độ FullScreenen EXIT Mode FullScreen

Ở đây, không sử dụng

localStorage.removeItem('store_name');

//e.g
localStorage.removeItem('name');
6 nhưng sử dụng phương thức
localStorage.removeItem('store_name');

//e.g
localStorage.removeItem('name');
7 vì chúng tôi không chắc chắn thứ tự chúng tôi có thể quyết định xóa từng phần tử khỏi cửa hàng
window.addEventListener('DOMContentLoaded', () =>{
        //show todos
    todos.forEach( todo => {
        let li = document.createElement('li');
        li.textContent =  todo;
        todosUl.appendChild(li);
        //delete todos
        li.addEventListener('dblclick', () => {
            todosUl.removeChild(li);
        })
    })

    const addTodos = e => {
    e.preventDefault();

    let li = document.createElement('li');
    li.textContent =  input.value;
    todos.push(input.value);
    todosUl.appendChild(li);
    input.value = '';
}
saveBtn.addEventListener('click', addTodos);
})
1.

Chúng tôi tìm thấy chỉ số cụ thể của

localStorage.setItem('store_name', 'data_name'); 
//e.g
localStorage.setItem('name', 'Ahmed');

4 mà chúng tôi muốn xóa khỏi
localStorage.getItem('store_name');

//e.g
localStorage.getItem('name'); //Ahmed
//or 
localStorage // all stores

4 bằng phương pháp
localStorage.clear();
1. Thêm mối nối nó từ mảng. Sau đó, tạo lại đối tượng
localStorage.getItem('store_name');

//e.g
localStorage.getItem('name'); //Ahmed
//or 
localStorage // all stores

4 sau khi sửa đổi.

Thuận lợi

Lần này, dữ liệu vẫn tồn tại ngay cả khi chúng tôi đóng và mở lại trình duyệt.

Bất lợi

Chúng tôi không thể lưu trữ các loại dữ liệu phức tạp bằng cách sử dụng

localStorage.getItem('store_name');

//e.g
localStorage.getItem('name'); //Ahmed
//or 
localStorage // all stores

4. Đó là nơi
localStorage.clear();
4 đến.

3. IndexedDB

Với

const todos = ['play piano', 'write some code', 'swim'];
7, chúng ta có thể lưu trữ các loại dữ liệu khác nhau dưới nhiều hình thức. Nó là một cơ sở dữ liệu miễn phí trong trình duyệt. Bộ lưu trữ không giới hạn ở các chuỗi như với
localStorage.getItem('store_name');

//e.g
localStorage.getItem('name'); //Ahmed
//or 
localStorage // all stores

4.

Vì nó lưu trữ dữ liệu không đồng bộ, chúng ta có thể sử dụng lời hứa để tương tác với cơ sở dữ liệu. Chúng tôi cần tải xuống một thư viện như

localStorage.clear();
7 của Jake Archibald để sử dụng API Promise. Trong bản demo đơn giản này, chúng tôi sẽ sử dụng API
const todos = ['play piano', 'write some code', 'swim'];
7, sử dụng các sự kiện thay vì lời hứa.

const todos = ['play piano', 'write some code', 'swim'];
7 hoạt động giống như cơ sở dữ liệu NoQuery, chẳng hạn như MongoDB.

Chúng tôi tạo một tên

const getTodos = () => {
    let todos;
    if(localStorage.getItem('todos') === null){
        todos = [];
    }else {
        todos = JSON.parse(localStorage.getItem('todos'));
    }
    return todos;
}

0. Thêm đối tượng
const getTodos = () => {
    let todos;
    if(localStorage.getItem('todos') === null){
        todos = [];
    }else {
        todos = JSON.parse(localStorage.getItem('todos'));
    }
    return todos;
}

1. Các cửa hàng đối tượng giống như các bảng trong MySQL hoặc các mô hình trong MongoDB.

Cấu trúc của các cửa hàng đến từ

const getTodos = () => {
    let todos;
    if(localStorage.getItem('todos') === null){
        todos = [];
    }else {
        todos = JSON.parse(localStorage.getItem('todos'));
    }
    return todos;
}

2. Trong MongoDB, chúng tôi sẽ gọi chúng là
const getTodos = () => {
    let todos;
    if(localStorage.getItem('todos') === null){
        todos = [];
    }else {
        todos = JSON.parse(localStorage.getItem('todos'));
    }
    return todos;
}

3.

Cơ sở dữ liệu (đối tượng) có một phương thức gọi là

const getTodos = () => {
    let todos;
    if(localStorage.getItem('todos') === null){
        todos = [];
    }else {
        todos = JSON.parse(localStorage.getItem('todos'));
    }
    return todos;
}

4 cho phép chúng tôi thực hiện CRUD trong
const todos = ['play piano', 'write some code', 'swim'];
7. Trong quá trình này, chúng tôi sử dụng
const getTodos = () => {
    let todos;
    if(localStorage.getItem('todos') === null){
        todos = [];
    }else {
        todos = JSON.parse(localStorage.getItem('todos'));
    }
    return todos;
}

6 để lặp qua các bản ghi trong lưu trữ đối tượng.

Để đơn giản hóa cơ sở dữ liệu phức tạp (dường như), chúng tôi sẽ tạo bốn chức năng như sau

// ConnectIdB ()

// addTodos ()

// gettodos ()

// Deletetodos ()

Đầu tiên, chúng tôi tạo một thể hiện toàn cầu của cơ sở dữ liệu vì chúng tôi sẽ sử dụng nó ở một vài nơi trong các chức năng sau.

const todos = ['play piano', 'write some code', 'swim'];
2

Nhập chế độ FullScreenen EXIT Mode FullScreen

Tiếp theo, chúng tôi kết nối với

const getTodos = () => {
    let todos;
    if(localStorage.getItem('todos') === null){
        todos = [];
    }else {
        todos = JSON.parse(localStorage.getItem('todos'));
    }
    return todos;
}

7 bằng hàm
const getTodos = () => {
    let todos;
    if(localStorage.getItem('todos') === null){
        todos = [];
    }else {
        todos = JSON.parse(localStorage.getItem('todos'));
    }
    return todos;
}

8.

const todos = ['play piano', 'write some code', 'swim'];
3

Nhập chế độ FullScreenen EXIT Mode FullScreen

Hãy mở phiên bản 1 của cơ sở dữ liệu

const getTodos = () => {
    let todos;
    if(localStorage.getItem('todos') === null){
        todos = [];
    }else {
        todos = JSON.parse(localStorage.getItem('todos'));
    }
    return todos;
}

9 bằng phương pháp
const saveTodos = inputData => {
    const todos = getTodos();
    todos.push(inputData);
    localStorage.setItem('todos', JSON.stringify(todos));
}
0.

Ở đây, chúng tôi nói về các phiên bản vì chúng tôi có thể nâng cấp cơ sở dữ liệu nếu chúng tôi thay đổi cấu trúc của nó. Tiếp theo, chúng tôi chạy ba sự kiện trên thể hiện cơ sở dữ liệu.

Đầu tiên, chúng tôi kiểm tra xem cơ sở dữ liệu mở có tồn tại hay tạo nó bằng sự kiện

const saveTodos = inputData => {
    const todos = getTodos();
    todos.push(inputData);
    localStorage.setItem('todos', JSON.stringify(todos));
}
1 không. Hoặc nếu chúng ta cố gắng mở cơ sở dữ liệu với phiên bản cao hơn phiên bản hiện có. Chúng tôi tạo tên của cửa hàng. Chúng tôi đã gọi nó là
const saveTodos = inputData => {
    const todos = getTodos();
    todos.push(inputData);
    localStorage.setItem('todos', JSON.stringify(todos));
}
2. Bạn có thể gọi nó là bất cứ thứ gì bạn muốn.

Tiếp theo, chúng tôi xác định một đối tượng có bàn phím và

const saveTodos = inputData => {
    const todos = getTodos();
    todos.push(inputData);
    localStorage.setItem('todos', JSON.stringify(todos));
}
3. Ở đây,
const saveTodos = inputData => {
    const todos = getTodos();
    todos.push(inputData);
    localStorage.setItem('todos', JSON.stringify(todos));
}
4 chứa ID duy nhất cho mỗi bản ghi trong cơ sở dữ liệu. Chúng tôi đang sử dụng
const saveTodos = inputData => {
    const todos = getTodos();
    todos.push(inputData);
    localStorage.setItem('todos', JSON.stringify(todos));
}
3 để cho
const todos = ['play piano', 'write some code', 'swim'];
7 tự động tăng nó. Sau đó, chúng tôi nói
const todos = ['play piano', 'write some code', 'swim'];
7 Dữ liệu thực tế (tên) mỗi bản ghi phải chứa.

Chúng tôi muốn lưu trữ nội dung (từ biểu mẫu), vì chúng tôi sẽ xác định khi lưu dữ liệu biểu mẫu thực tế. Dữ liệu không phải là duy nhất vì chúng tôi có thể cho phép cơ sở dữ liệu lưu một bản ghi khác có cùng tên.

Thứ hai, nếu có lỗi khi chúng tôi cố gắng mở cơ sở dữ liệu, chúng tôi sẽ chạy sự kiện lỗi và ghi lại lỗi trên bảng điều khiển. Cuối cùng, khi thành công, chúng tôi lưu trữ thuộc tính kết quả của cơ sở dữ liệu trong biến

const getTodos = () => {
    let todos;
    if(localStorage.getItem('todos') === null){
        todos = [];
    }else {
        todos = JSON.parse(localStorage.getItem('todos'));
    }
    return todos;
}

7. Sau đó, chúng ta có thể hiển thị kết quả bằng hàm
const saveTodos = inputData => {
    const todos = getTodos();
    todos.push(inputData);
    localStorage.setItem('todos', JSON.stringify(todos));
}
9.

Trước khi nhận được

window.addEventListener('DOMContentLoaded', () =>{
        //show todos
    todos.forEach( todo => {
        let li = document.createElement('li');
        li.textContent =  todo;
        todosUl.appendChild(li);
        //delete todos
        li.addEventListener('dblclick', () => {
            todosUl.removeChild(li);
        })
    })

    const addTodos = e => {
    e.preventDefault();

    let li = document.createElement('li');
    li.textContent =  input.value;
    todos.push(input.value);
    todosUl.appendChild(li);
    input.value = '';
}
saveBtn.addEventListener('click', addTodos);
})
1, chúng ta hãy tạo chúng từ biểu mẫu và lưu chúng.

//addTodos()

const todos = ['play piano', 'write some code', 'swim'];
4

Nhập chế độ FullScreenen EXIT Mode FullScreen

Đầu tiên, chúng tôi ngăn biểu mẫu từ hành vi mặc định của nó là làm mới trang cho mỗi lần gửi bằng

  saveTodos(input.value);
1.

Tiếp theo, chúng tôi tạo một giao dịch

  saveTodos(input.value);
2 trong cửa hàng
const saveTodos = inputData => {
    const todos = getTodos();
    todos.push(inputData);
    localStorage.setItem('todos', JSON.stringify(todos));
}
2 được tạo trước đây của chúng tôi. Tiếp theo, chúng tôi tạo một bản ghi tạo mới và lưu trữ nó trong cửa hàng.

Nếu yêu cầu thành công, chúng tôi xóa biểu mẫu sẵn sàng cho đầu vào hình thức sau. Khi giao dịch đã được hoàn thành trong cơ sở dữ liệu, chúng tôi có thể đọc dữ liệu.completed in the database, we can read the data.

Nếu chúng tôi không hoàn thành giao dịch, chúng tôi sẽ chạy một sự kiện lỗi và dừng thực hiện mã tiếp theo.

//getTodos()

Chúng tôi chạy một vòng lặp trong thời gian để loại bỏ

  saveTodos(input.value);
4 hiện tại của
window.addEventListener('DOMContentLoaded', () =>{
        //show todos
    todos.forEach( todo => {
        let li = document.createElement('li');
        li.textContent =  todo;
        todosUl.appendChild(li);
        //delete todos
        li.addEventListener('dblclick', () => {
            todosUl.removeChild(li);
        })
    })

    const addTodos = e => {
    e.preventDefault();

    let li = document.createElement('li');
    li.textContent =  input.value;
    todos.push(input.value);
    todosUl.appendChild(li);
    input.value = '';
}
saveBtn.addEventListener('click', addTodos);
})
2 để tránh sao chép bản ghi. Tiếp theo, chúng tôi nhận được cửa hàng mục tiêu.

Sử dụng phương pháp

const getTodos = () => {
    let todos;
    if(localStorage.getItem('todos') === null){
        todos = [];
    }else {
        todos = JSON.parse(localStorage.getItem('todos'));
    }
    return todos;
}

6 và sự kiện thành công, tạo
localStorage.setItem('store_name', 'data_name'); 
//e.g
localStorage.setItem('name', 'Ahmed');

4 cho mỗi bản ghi bằng ID duy nhất mà chúng tôi đã lưu trước đó.

Từ đây, chúng ta có thể quyết định xóa danh sách bằng cách sử dụng hàm xóa gắn với mỗi

localStorage.setItem('store_name', 'data_name'); 
//e.g
localStorage.setItem('name', 'Ahmed');

4. Hãy nhớ kết thúc
const getTodos = () => {
    let todos;
    if(localStorage.getItem('todos') === null){
        todos = [];
    }else {
        todos = JSON.parse(localStorage.getItem('todos'));
    }
    return todos;
}

6 với
const todos = ['play piano', 'write some code', 'swim'];
00 để cho phép mã tiến hành tạo và xóa
localStorage.setItem('store_name', 'data_name'); 
//e.g
localStorage.setItem('name', 'Ahmed');

4 sau đây.

const todos = ['play piano', 'write some code', 'swim'];
5

Nhập chế độ FullScreenen EXIT Mode FullScreen

//deleteTodos()

Giống như

const saveTodos = inputData => {
    const todos = getTodos();
    todos.push(inputData);
    localStorage.setItem('todos', JSON.stringify(todos));
}
9, chúng tôi bắt đầu giao dịch
  saveTodos(input.value);
2 trên cửa hàng đối tượng. Chuyển đổi từng ID của ____ 104 thành một số và tìm khớp của nó với số được lưu trữ trong cơ sở dữ liệu. Sau đó, xóa nó.

const todos = ['play piano', 'write some code', 'swim'];
6

Nhập chế độ FullScreenen EXIT Mode FullScreen

Và Voila! Chúng tôi đã thực hiện một bản cập nhật đơn giản cho

const todos = ['play piano', 'write some code', 'swim'];
7.

Hãy nhớ rằng, bạn có thể lưu trữ hình ảnh, video và hình ảnh trong

const todos = ['play piano', 'write some code', 'swim'];
7 như bạn sẽ làm trong một môi trường phía máy chủ điển hình.

Bất lợi

Điểm yếu chính của

const todos = ['play piano', 'write some code', 'swim'];
7 là nó có thể phức tạp để sử dụng.

Sự kết luận

Bài viết này nhằm mục đích cung cấp cho bạn một cái nhìn tổng quan về các cách bạn có thể sử dụng JavaScript để lưu trữ dữ liệu ở phía máy khách. Bạn có thể đọc thêm về từng phương pháp và áp dụng nó theo nhu cầu của bạn.

Chúng ta có thể lưu trữ dữ liệu bằng JavaScript không?

JavaScript cho phép chúng tôi lưu trữ dữ liệu trong trình duyệt bằng API lưu trữ cục bộ. Tại đây, bạn có thể sử dụng LocalStorage và SessionStorage. Các đối tượng cho phép chúng tôi lưu trữ dữ liệu (trong các cặp khóa/giá trị) và cập nhật nó từ lưu trữ của trình duyệt. Để xem dữ liệu, hãy mở trình duyệt của bạn.. Here, you can use LocalStorage and SessionStorage . The objects let us store data (in key/value pairs) and update it from the browser's storage. To view the data, open your browser.

Làm thế nào chúng ta có thể lưu trữ dữ liệu trong JavaScript mà không cần cơ sở dữ liệu?

Bạn có thể sử dụng lưu trữ web. Từ W3Schools: Với lưu trữ web, các ứng dụng web có thể lưu trữ dữ liệu cục bộ trong trình duyệt của người dùng. Trước HTML5, dữ liệu ứng dụng phải được lưu trữ trong cookie, bao gồm trong mọi yêu cầu của máy chủ.

Làm thế nào JavaScript có thể lưu trữ dữ liệu tạm thời?

Có nhiều cách khác nhau để làm điều này, tùy thuộc vào yêu cầu của bạn:..
Chúng ta có thể sử dụng các biến không đổi, tạo một file hằng.js và có thể được sử dụng để lưu trữ dữ liệu dưới dạng. ....
Sử dụng cookiestore, sử dụng: ....
Sử dụng lưu trữ cục bộ: ....
Tùy chọn là ghi dữ liệu vào một tệp ..

Làm thế nào để bạn lưu trữ dữ liệu?

Dữ liệu có thể được ghi lại và lưu trữ trong ba biểu mẫu chính: lưu trữ tệp, lưu trữ khối và lưu trữ đối tượng ...
Lưu trữ tập tin.Lưu trữ tệp, còn được gọi là cấp độ tệp hoặc lưu trữ dựa trên tệp, là một phương pháp lưu trữ phân cấp được sử dụng để sắp xếp và lưu trữ dữ liệu.....
Lưu trữ khối.....
Lưu trữ đối tượng ..

Làm thế nào để JavaScript lưu trữ dữ liệu trong bộ đệm trình duyệt?

Lưu trữ dữ liệu đơn giản - Lưu trữ web..
Đầu tiên, hãy chuyển đến mẫu trống lưu trữ web của chúng tôi trên GitHub (mở cái này trong một tab mới) ..
Mở bảng điều khiển JavaScript của các công cụ phát triển của trình duyệt của bạn ..
Tất cả dữ liệu lưu trữ web của bạn được chứa trong hai cấu trúc giống như đối tượng bên trong trình duyệt: sessionStorage và localStorage ..

Làm cách nào để lưu trữ dữ liệu trong trình duyệt?

3 cách để lưu trữ dữ liệu trong trình duyệt là cookie, lưu trữ cục bộ và lưu trữ phiên.Tùy thuộc vào nhu cầu bất kỳ một trong số chúng được sử dụng để lưu trữ dữ liệu trong trình duyệt.Trong bài viết hôm nay, chúng tôi sẽ thảo luận về so sánh chuyên sâu giữa lưu trữ cục bộ, lưu trữ phiên và cookie.Cookies, Local Storage, and Session Storage. Depending on the needs any one of them is used to store data in the browser. In today's article, we will discuss an in-depth comparison between local storage, session storage, and cookies.