簡體   English   中英

在網頁上本地存儲用戶輸入的數據的最佳方法是什么?

[英]What is the best way to locally store user-entered data on a web page?

我正在開發一個Web應用程序,該應用程序基本上允許用戶輸入有關產品的數據,然后將其添加到表格的網頁中。 我想將此信息保存在某種文件中(目前僅在本地計算機上),以便用戶可以打開他或她先前創建的條目。

這是html頁面的精簡版本:

<!doctype html>
<html lang="en">
<head>
        <meta charset="utf-8">


</head>
<body>
    <div>
        <table id="itemsTable">
            <tr>
                <th>Date Added</th>
                <th>Item Description</th>
            </tr>
            </table>

    </div>
     <div id="itemInput">

         <h3>Add Item</h3>
             Date Added:<input type="date" id="dateAdded">
        Description:<input type="text" id="description">
<input type="button" value="Add Row" onclick="addRowFunction();">
<input type="button" value="Delete Selected" onclick="deleteRowFunction();">        
     </div>
</html>

然后,我將使用一些JavaScript來評估和解釋客戶端數據。 我正在尋找想法來存儲記錄的條目(本地)。 不僅如此,我還在尋找有關如何刪除已存儲信息的建議。

編輯:

根據您的要求,以下是我的JS代碼的片段:

//Striped-down object
function Item (dateListed, description) {
    this.dateListed = dateListed;
    this.description = description;

}

//Simple function to take data from form, create object, add to table.
function addItem() {
    var dateAdded = document.getElementById('dateAdded').value;
    var description = document.getElementById('description').value;

    // I realize that using an object in this striped-down version is kind of 
    // unnecessary, but in the full code it makes more sense.    
    var newItem = new Item(dateAdded, description);

    table = document.getElementById('itemsTable');
    var row = table.insertRow(1);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);

    cell1.innerHTML = newItem.dateListed;
    cell2.innerHTML = newItem.description;
}

如果您不存儲太多數據,則localStorage可以工作,但是IndexedDB可能是一個更好的選擇,它具有更高的默認存儲限制,並允許您以更結構化的方式存儲數據。 IndexedDB允許您存儲對象以及可以通過結構化克隆算法克隆的任何其他東西,而無需手動序列化/反序列化(localStorage只能存儲字符串)。

IndexedDB有點復雜,使用起來很麻煩,使用抽象層可能是個好主意。 PouchDB是一個相當流行的庫,它會為您處理詳細信息。 它在后台使用IndexedDB(或其他類似技術,具體取決於當前瀏覽器支持的內容),並為您提供更好的API。 使用PouchDB的好處之一是,如果最終在服務器上使用了CouchDB,則PouchDB實際上可以與其同步。

我建議localStorageindexedDb

如果涉及的數據操作非常有限,則localStorage將很有用。 (可以很容易地完成CRUD操作),但是如果涉及到更復雜的操作,請使用indexedDb

您是否已查看window.localStorage 這是在現代瀏覽器中,它允許您存儲對象的字符串表示形式。 請參閱有關MDN的規范

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM