082_html5Web存储
1. 在客戶端存儲數(shù)據(jù)
1.1. html5提供了兩種在客戶端存儲數(shù)據(jù)的新方法:
?1.1.1. localStorage: 沒有時間限制的數(shù)據(jù)存儲。
?1.1.2. sessionStorage: 針對一個session的數(shù)據(jù)存儲。
1.2. 之前, 這些都是由cookie完成的。但是cookie不適合大量數(shù)據(jù)的存儲, 因為它們由每個服務器請求來傳遞, 這使得cookie速度很慢而且效率也不高。
1.3. 在html5中, 數(shù)據(jù)不是由每個服務器請求傳遞的, 而是只有在請求時使用數(shù)據(jù)。它使在不影響網(wǎng)站性能的情況下存儲大量數(shù)據(jù)成為可能。
1.4. 對于不同的網(wǎng)站, 數(shù)據(jù)存儲于不同的區(qū)域, 并且一個網(wǎng)站只能訪問其自身的數(shù)據(jù)。
1.5. html5使用JavaScript來存儲和訪問數(shù)據(jù)。
2. localStorage方法
2.1. localStorage方法存儲的數(shù)據(jù)沒有時間限制。第二天、第二周或下一年之后, 數(shù)據(jù)依然可用。
2.2. 如何創(chuàng)建和訪問localStorage:
<!DOCTYPE html> <html><head><meta charset="utf-8" /><title>localStorage方法</title></head><body><script type="text/javascript">// 檢查瀏覽器支持if (typeof(Storage) !== "undefined") {localStorage.lastname = "Smith";document.write(localStorage.lastname + '<br />');// 儲存localStorage數(shù)據(jù)localStorage.setItem("lastname", "Gates");// 訪問localStorage數(shù)據(jù)document.write(localStorage.getItem("lastname"));} else {document.write("抱歉! 您的瀏覽器不支持Web Storage...");}</script></body> </html>2.3. 下面的例子對用戶訪問頁面的次數(shù)進行計數(shù):
<!DOCTYPE html> <html><head><meta charset="utf-8" /><title>localStorage方法頁面訪問次數(shù)</title></head><body><script type="text/javascript">if (typeof(Storage) !== "undefined") {if (localStorage.pagecount) {localStorage.pagecount = Number(localStorage.pagecount) + 1;} else {localStorage.pagecount = 1;}document.write("Visits: " + localStorage.pagecount + " time(s).");} else {document.write("抱歉! 您的瀏覽器不支持Web Storage...");}</script> <p>刷新頁面會看到計數(shù)器在增長。</p><p>請關閉瀏覽器窗口, 然后再試一次, 計數(shù)器會繼續(xù)計數(shù)。</p></body> </html>3. sessionStorage方法
3.1. sessionStorage方法針對一個session進行數(shù)據(jù)存儲。當用戶關閉瀏覽器窗口后, 數(shù)據(jù)會被刪除。
3.2. 如何創(chuàng)建并訪問一個sessionStorage:
<!DOCTYPE html> <html><head><meta charset="utf-8" /><title>sessionStorage方法</title></head><body><div id="result"></div><script>// 檢查瀏覽器支持if (typeof(Storage) !== "undefined") {sessionStorage.lastname = "Smith";document.write(sessionStorage.lastname + '<br />');// 儲存sessionStorage數(shù)據(jù)sessionStorage.setItem("firstname", "Gates");// 訪問sessionStorage數(shù)據(jù)document.write(sessionStorage.getItem("firstname"));} else {document.write("抱歉! 您的瀏覽器不支持Web Storage...");}</script></body> </html>3.3. 下面的例子對用戶訪問頁面的次數(shù)進行計數(shù):
<!DOCTYPE html> <html><head><meta charset="utf-8" /><title>sessionStorage方法頁面訪問次數(shù)</title></head><body><script type="text/javascript">if (typeof(Storage) !== "undefined") {if (sessionStorage.pagecount){sessionStorage.pagecount = Number(sessionStorage.pagecount) + 1;} else {sessionStorage.pagecount = 1;}document.write("Visits: " + sessionStorage.pagecount + " time(s).");} else {document.write("抱歉! 您的瀏覽器不支持Web Storage...");}</script> <p>刷新頁面會看到計數(shù)器在增長。</p><p>請關閉瀏覽器窗口, 然后再試一次, 計數(shù)器已經(jīng)重置了。</p></body> </html>總結
以上是生活随笔為你收集整理的082_html5Web存储的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 081_html5地理定位
- 下一篇: 083_html5应用程序缓存