html5中的web存储功能

网页中的存储可以存放在客户端,也可以存放在服务器端。虽然存放在服务器非常的安全,但是如果每次都从服务器去读取数据,进行I/O操作,那么我想服务器的压力恐怕不是一点点的大。所以有人就考虑把部分信息存放在客户端,减轻服务器的压力。

其中web存储又分为本地存储和回话存储。他们的主要区别是本地存储就是存放在浏览器中,只要你不去清除,那么一直存在,适合存放一些长期保持的数据。而对于会话存储只要你把浏览器关闭,那么这些数据就不存在了(被浏览器清除)。根据他们的特点,我们可以知道本地存储主要是存放访客在将来还可以看到的数据,而对于会话存储则存放一些从一个页面传递给下一个页面的一些内容。

对于我们的代码编写而言,他们的操作一模一样,所以下面就只对本地存储做介绍。接下来通过代码说明:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<input id="name" type="text">
	<button id="save">保存</button>
	<button id="get">取值</button>
	<button id="delete">删除</button>
	<script type="text/javascript">
		window.οnlοad=function(){
			var oName = document.getElementById("name");
			var oSave = document.getElementById("save");
			var oGet = document.getElementById("get");
			var oDelete = document.getElementById("delete");
			oSave.οnclick=function(){
				// 存放主要是通过键值对的方式,如果是会话存放,则是sessionStorage
				// 通过localStorage.setItem存放,通过localStorage.getItem获取
				localStorage.setItem("username",oName.value);
				oName.value = "";
			}
			oGet.οnclick=function(){
				if(localStorage.getItem("username")==null){
					alert("你没有保存这个值");
				}else{
					var name = localStorage.getItem("username");
					alert(name+"");
				}
			}
			oDelete.οnclick=function(){
				// 如果想要删除全部的话,那么就使用localStorage.clear();
				localStorage.removeItem("username");
			}
		}
	</script>
</body>
</html>

介绍了上面最基本的读取,下面总结一下读取所有的存储内容,如果读取。因为我们有时候忘记了key值,那么就只有遍历出来看看,当然也可以通过其他方式查看

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<ul id="datalist">
	</ul>
	<script type="text/javascript">
		window.οnlοad=function(){
			localStorage.setItem("username","xiaoD");
			localStorage.setItem("password","123");
			localStorage.setItem("gender","男");
			localStorage.setItem("age","21");
			var oItem = document.getElementById("datalist");
			for(var i=localStorage.length-1;i>=0;i--){
				var key = localStorage.key(i);
				var item = localStorage.getItem(key);
				var newItem = document.createElement("li");
				newItem.innerHTML = key + "--" + item;
				oItem.appendChild(newItem);
			}
		}
	</script>
</body>
</html>

一切都很好,用的很舒服,记得曾经有位老师曾经说过,凡是我们觉得好用的东西,总是会有那么一点bug。这个也不例外,具体什么问题呢,也就是我们再读取一个数字或者时间的时候,读取出来的是字符串,见下面代码:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<input id="num" type="text">
	<input id="time" type="text">
	<script type="text/javascript">
		window.οnlοad=function(){
			localStorage.setItem("age",21);
			var oNum = document.getElementById("num");
			oNum.value = localStorage.getItem("age")+5;  //最后的结果为215
			//解决办法
			oNum.value = Number(localStorage.getItem("age"))+5;//最后的结果为26

			var today = new Date();
			var todayString = today.getFullYear()+"-"+Number(today.getMonth()+1)+"-"+today.getDate();
			localStorage.setItem("time",todayString);
			var oTime = document.getElementById("time");
			oTime.value = new Date(localStorage.getItem("time")).getFullYear();//转换
		}
	</script>
</body>
</html>


在测试的时候需要注意,在本地测试的时候可能会出错,这时候可以放在服务器上测试。


每每听到客户抱怨自己修改和很久的数据由于自己的一个误操作而丢失时,总想让web页面也有像window窗体一样具有提示保存的功能。所以,经过一段时间的研究以后终于实现了这个功能!============ checksave.js =======================<!-- The JavaScript is used in show a message to prompt user to save data.--><script language="JScript">function window::onbeforeunload(){if (typeof(document.all[‘txtCheckFlag‘]) != "undefined") // to detect whether this page need prompt the save message!{ if (event.clientY<0 && event.clientX>document.body.clientWidth-20 || event.clientY<0 && event.clientX<20 || event.altKey || event.clientY>document.body.clientHeight) event.returnValue="If you have modified some data, you need push the save button to save them. Do you want to save?";}}</script><script language=javascript><!-- function checksave(arg){if (typeof(document.all[‘txtCheckFlag‘]) != "undefined") // to detect whether this page need prompt the save message! { // If need document.all["txtCheckFlag"].value=arg; document.forms(0).submit(); return false; }else // If does not need { window.location=arg; return true; }}function showsavemessage(arg){if (window.confirm("Save Change?")) { document.all["txtSave"].value="1"; document.forms(0).submit(); return false; }else { if (arg == ".") { return true; } else { window.location=arg; return false; } }}//--></script>======== test.aspx ===============<%@ Page Language="vb" AutoEventWireup="false" Codebehind="test.aspx.vb" Inherits="Test.test" smartNavigation="True" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML> <HEAD> <title>test</title> <meta content="Microsoft Visual Studio.NET 7.0" name="GENERATOR"> <meta content="Visual Basic 7.0" name="CODE_LANGUAGE"> <meta content="JavaScript" name="vs_defaultClientScript"> <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema"> <!--#include file="checksave.js"--> </HEAD> <body MS_POSITIONING="GridLayout" onload="pageload()"> <form id="Form1" method="post" runat="server"> <a onclick="javascript:return checksave(this.href)" href=DownloadFiles1DownloadFiles1DownloadFiles1"TestNoNeedCheck.aspx">sohu</a><BR> <a onclick="javascript:return checksave(this.href)" href=DownloadFiles1DownloadFiles1DownloadFiles1"TestNoNeedCheck.aspx">yahoo</a><BR> <a onclick="javascript:return checksave(this.href)" href=DownloadFiles1DownloadFiles1DownloadFiles1"TestNoNeedCheck.aspx">MTR</a> <asp:textbox id="txtCheckFlag" style="Z-INDEX: 101; LEFT: 213px; POSITION: absolute; TOP: 91px" runat="server"></asp:textbox><asp:textbox id="txtSave" style="Z-INDEX: 102; LEFT: 211px; POSITION: absolute; TOP: 139px" runat="server"></asp:textbox><asp:linkbutton id="LinkButton1" style="Z-INDEX: 103; LEFT: 150px; POSITION: absolute; TOP: 204px" runat="server">LinkButton</asp:linkbutton> <asp:Button id="Button1" style="Z-INDEX: 104; LEFT: 238px; POSITION: absolute; TOP: 271px" runat="server" Text="Button"></asp:Button></form> </body></HTML>======== test.aspx.vb ===============Public Class test Inherits System.Web.UI.Page Protected WithEvents txtSave As System.Web.UI.WebControls.TextBox Protected WithEvents LinkButton1 As System.Web.UI.WebControls.LinkButton Protected WithEvents Button1 As System.Web.UI.WebControls.Button Protected WithEvents txtCheckFlag As System.Web.UI.WebControls.TextBox#Region " Web Form Designer Generated Code " ‘This call is required by the Web Form Designer. <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() End Sub Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init ‘CODEGEN: This method call is required by the Web Form Designer ‘Do not modify it using the code editor. InitializeComponent() End Sub#End Region Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ‘Put user code to initialize the page here txtSave.Style.Item("display") = "none" txtCheckFlag.Style.Item("display") = "none" LinkButton1.Attributes("onclick") = "javascript:return checksave(this.href)" ‘ Page.RegisterStartupScript("Prompt", "<script language=""javascript"">function pageload() { }</script>") End Sub Private Sub txtCheckFlag_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtCheckFlag.TextChanged Session("URL") = txtCheckFlag.Text If checkdata() Then ‘Session("Data") = Me.Data If InStr(txtCheckFlag.Text, "__doPostBack") > 0 Then Page.RegisterStartupScript("warning", "<script language=""javascript"">function pageload() {if (showsavemessage(‘.‘)) " + Session("URL") + ";}</script>") Else Page.RegisterStartupScript("warning", "<script language=""javascript"">function pageload() {showsavemessage(‘" + Session("URL") + "‘);}</script>") End If Else If InStr(txtCheckFlag.Text, "__doPostBack") > 0 Then Session("URL") = Replace(txtCheckFlag.Text, "javascript:", "") Page.RegisterStartupScript("warning", "<script language=""javascript"">function pageload() {" + Session("URL") + ";}</script>") Else If InStr(txtCheckFlag.Text, "javascript:") > 0 Then Session("URL") = Replace(txtCheckFlag.Text, "javascript:", "") Page.RegisterStartupScript("Redirect", "<script language=""javascript"">function pageload() {" + Session("URL") + ";}</script>") Else Page.RegisterStartupScript("Redirect", "<script language=""javascript"">function pageload() {window.location=‘" + Session("URL") + "‘;}</script>") Response.End() End If End If End If End Sub Private Sub txtSave_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtSave.TextChanged If savedata() = False Then txtSave.Text = "" txtCheckFlag.Text = "" Exit Sub End If Me.ViewState("flag") = True If InStr(txtCheckFlag.Text, "__doPostBack") > 0 Then Page.RegisterStartupScript("TxtSave", "<script language=""javascript"">" + Session("URL") + "</script>") Else If InStr(txtCheckFlag.Text, "javascript:") > 0 Then Session("URL") = Replace(txtCheckFlag.Text, "javascript:", "") Page.RegisterStartupScript("TxtSave", "<script language=""javascript"">function pageload() {" + Session("URL") + ";}</script>") Else Page.RegisterStartupScript("Redirect", "<script language=""javascript"">function pageload() {window.location=‘" + Session("URL") + "‘;}</script>") ‘Response.Redirect(Session("URL")) ‘Response.End() End If End If txtSave.Text = "" txtCheckFlag.Text = "" End Sub Private Function checkdata() As Boolean ‘check whether user really had modified the data Return True End Function Private Function savedata() As Boolean ‘do save data here! Return True End Function Private Sub LinkButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LinkButton1.Click If Me.ViewState("flag") = True Then Page.RegisterStartupScript("Redict", "<script language=""javascript"">function pageload() {window.location=‘TestNoNeedCheck.aspx‘;}</script>") Else Page.RegisterStartupScript("Redict", "<script language=""javascript"">function pageload() {window.location=‘TestNoNeedCheck.aspx‘;}</script>") End If End SubEnd Class
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值