离线网络应用程序。如何存储数据?

Her*_*tzu 6 javascript local-storage offlineapps

介绍:

我想开发一个 webapp 来管理体育比赛。它必须能够完全离线运行,在本地存储数据并在有可用互联网连接时通过 AJAX 在线发布结果 - 这可能是后天。

题:

如何使用Javascript存储数据?

附加说明:

  • 我不想使用任何服务器端技术。
  • 它必须像数据库一样安全。我读过关于 cookie 和 html5 存储的文章,但没有一个听起来令人信服。

Pra*_*man 2

如果您支持现代浏览器,则可以使用HTML5 本地存储

持久本地存储是本机客户端应用程序相对于 Web 应用程序具有优势的领域之一。对于本机应用程序,操作系统通常提供一个抽象层,用于存储和检索特定于应用程序的数据,例如首选项或运行时状态。这些值可能存储在注册表、INI 文件、XML 文件或根据平台约定的其他位置。如果您的本机客户端应用程序需要键/值对之外的本地存储,您可以嵌入自己的数据库、发明自己的文件格式或任意数量的其他解决方案。

例子

// Save data to a the current session's store
sessionStorage.setItem("username", "John");

// Access some stored data
alert( "username = " + sessionStorage.getItem("username"));

// Get the text field that we're going to track
var field = document.getElementById("field");

// See if we have an autosave value
// (this will only happen if the page is accidentally refreshed)
if ( sessionStorage.getItem("autosave")) {
   // Restore the contents of the text field
   field.value = sessionStorage.getItem("autosave");
}

// Check the contents of the text field every second
setInterval(function(){
   // And save the results into the session storage object
   sessionStorage.setItem("autosave", field.value);
}, 1000);
Run Code Online (Sandbox Code Playgroud)

浏览器兼容性


旧版浏览器

使用Polyfill