在JavaScript中,進行數據存儲通常有以下幾種方法:
// 存儲數據
localStorage.setItem('key', 'value');
// 讀取數據
const value = localStorage.getItem('key');
// 刪除數據
localStorage.removeItem('key');
// 清空所有數據
localStorage.clear();
// 存儲數據
sessionStorage.setItem('key', 'value');
// 讀取數據
const value = sessionStorage.getItem('key');
// 刪除數據
sessionStorage.removeItem('key');
// 清空所有數據
sessionStorage.clear();
// 打開數據庫
const request = indexedDB.open('myDatabase', 1);
request.onupgradeneeded = (event) => {
const db = event.target.result;
const objectStore = db.createObjectStore('myObjectStore', { keyPath: 'id' });
};
request.onsuccess = (event) => {
const db = event.target.result;
const transaction = db.transaction(['myObjectStore'], 'readwrite');
const objectStore = transaction.objectStore('myObjectStore');
// 添加數據
objectStore.add({ id: 1, value: 'example' });
// 讀取數據
const getRequest = objectStore.get(1);
getRequest.onsuccess = (event) => {
console.log(event.target.result); // 輸出:{ id: 1, value: 'example' }
};
// 更新數據
const updateRequest = objectStore.put({ id: 1, value: 'updated example' });
updateRequest.onsuccess = () => {
console.log('Data updated successfully');
};
// 刪除數據
const deleteRequest = objectStore.delete(1);
deleteRequest.onsuccess = () => {
console.log('Data deleted successfully');
};
};
fetch('https://example.com/api/saveData', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
key1: 'value1',
key2: 'value2',
}),
})
.then((response) => response.json())
.then((result) => {
console.log('Data sent successfully:', result);
})
.catch((error) => {
console.error('Error sending data:', error);
});
根據你的需求和場景,可以選擇合適的數據存儲方法。在大多數情況下,Local Storage 和 Session Storage 對于存儲爬取到的數據就足夠了。如果需要存儲大量結構化數據,可以使用 IndexedDB。如果需要將數據發送到服務器進行存儲,可以使用 AJAX 或 Fetch API。