在网页上本地存储用户输入数据的最佳方法是什么?

时间:2015-01-16 05:28:57

标签: javascript html5 storage

我正在开发基本上允许用户输入产品数据然后将其添加到表格中的网页的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;
}

3 个答案:

答案 0 :(得分:1)

如果您没有存储太多数据,

localStorage可以正常工作,但IndexedDB可能是更好的选择,它具有更高的默认存储限制,并允许您以更结构化的方式存储数据。 IndexedDB允许您存储对象以及structured cloning algorithm可以克隆的任何其他内容,而无需手动序列化/反序列化(localStorage只能存储字符串)。

IndexedDB有点复杂,可能很难处理,使用抽象层可能是个好主意。 PouchDB是一个相当受欢迎的图书馆,负责处理您的详细信息。在引擎盖下它使用IndexedDB(或其他类似技术,具体取决于当前浏览器支持的内容),并为您提供了更好的API。使用PouchDB的一个好处是,如果您最终在服务器上使用CouchDB,PouchDB实际上可以与它同步。

答案 1 :(得分:1)

我建议localStorageindexedDb

如果涉及非常有限的数据操作, localStorage 将非常有用。 ( CRUD 操作可以在此轻松完成),但如果涉及更复杂的操作,请使用 indexedDb

答案 2 :(得分:0)

你有没有看过window.localStorage?这是在现代浏览器中,允许您存储对象的字符串表示。 See the spec on MDN

相关问题