JavaScript 2.6 js操作localStorage/sessionStorage

一、localStorage/sessionStorage

1、localStorage(本地存储)和sessionStorage(会话存储)均提供了键值对的方式存储数据,大小一般在5MB。

2、localStorage是存储在本地,不存在失效时间,只能remove。

3、sessionStorage是会话存储,浏览器关闭后,数据便丢失。

4、两者都遵守同源策略,但是sessionStorage在不同的页签下是不可共享的,localStorage则是共享的。

5、两者均只支持以字符串的方式进行存储。

二、常用方法

//存值
localStorage.setItem(key,value);
//取值
localStorage.getItem(key);
//移除
localStorage.removeItem(key);
//全部清除
localStorage.clear();
//通过索引获取key
localStorage.key(index);

localStorage和sessionStorage的方法是一致的

三、以json方式进行存储

var cast = {
    "Adm. Adama" : "Edward James Olmos",
    "President Roslin" : "Mary McDonnell",
    "Captain Adama" : "Jamie Bamber",
    "Gaius Baltar" : "James Callis",
    "Number Six" : "Tricia Helfer",
    "Kara Thrace" : "	Katee Sackhoff"
};

// Stores the JavaScript object as a string
localStorage.setItem("cast", JSON.stringify(cast));

// Parses the saved string into a JavaScript object again 
JSON.parse(localStorage.getItem("cast"));

四、存储图片及发送请求

a.js

(function () {
    // localStorage with image
    var storageFiles = JSON.parse(localStorage.getItem("storageFiles")) || {},
        elephant = document.getElementById("elephant"),
        storageFilesDate = storageFiles.date,
        date = new Date(),
        todaysDate = (date.getMonth() + 1).toString() + date.getDate().toString();

    // Compare date and create localStorage if it's not existing/too old   
    if (typeof storageFilesDate === "undefined" || storageFilesDate < todaysDate) {
        // Take action when the image has loaded
        elephant.addEventListener("load", function () {
            var imgCanvas = document.createElement("canvas"),
                imgContext = imgCanvas.getContext("2d");

            // Make sure canvas is as big as the picture
            imgCanvas.width = elephant.width;
            imgCanvas.height = elephant.height;

            // Draw image into canvas element
            imgContext.drawImage(elephant, 0, 0, elephant.width, elephant.height);

            // Save image as a data URL
            storageFiles.elephant = imgCanvas.toDataURL("image/png");

            // Set date for localStorage
            storageFiles.date = todaysDate;

            // Save as JSON in localStorage
            try {
                localStorage.setItem("storageFiles", JSON.stringify(storageFiles));
            }
            catch (e) {
                    console.log("Storage failed: " + e);                
            }
        }, false);

        // Set initial image src    
        elephant.setAttribute("src", "elephant.png");
    }
    else {
        // Use image from localStorage
        elephant.setAttribute("src", storageFiles.elephant);
    }

    // Getting a file through XMLHttpRequest as an arraybuffer and creating a Blob
    var rhinoStorage = localStorage.getItem("rhino"),
        rhino = document.getElementById("rhino");
    if (rhinoStorage) {
        // Reuse existing Data URL from localStorage
        rhino.setAttribute("src", rhinoStorage);
    }
    else {
        // Create XHR, BlobBuilder and FileReader objects
        var xhr = new XMLHttpRequest(),
            blob,
            fileReader = new FileReader();

        xhr.open("GET", "rhino.png", true);
        // Set the responseType to arraybuffer. "blob" is an option too, rendering BlobBuilder unnecessary, but the support for "blob" is not widespread enough yet
        xhr.responseType = "arraybuffer";

        xhr.addEventListener("load", function () {
            if (xhr.status === 200) {
                // Create a blob from the response
                blob = new Blob([xhr.response], {type: "image/png"});

                // onload needed since Google Chrome doesn't support addEventListener for FileReader
                fileReader.onload = function (evt) {
                    // Read out file contents as a Data URL
                    var result = evt.target.result;
                    // Set image src to Data URL
                    rhino.setAttribute("src", result);
                    // Store Data URL in localStorage
                    try {
                        localStorage.setItem("rhino", result);
                    }
                    catch (e) {
                        console.log("Storage failed: " + e);
                    }
                };
                // Load blob as Data URL
                fileReader.readAsDataURL(blob);
            }
        }, false);
        // Send XHR
        xhr.send();
    }
})();

b.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>HTML5 demo with localStorage and saving images and files in it</title>
        <link rel="stylesheet" href="css/base.css" type="text/css" media="screen">
    </head>

    <body>

        <div class="container">

            <header class="header" role="banner">
                <h1>HTML5 demo with localStorage and saving images and files in it</h1>
            </header>

            <div class="main">
                <article class="main-content" role="main">

                    <aside class="additional-content" aria-live="polite" aria-relevant="additions" aria-atomic="true">
                        <p>This is a demo page displaying how you can use localStorage to save image files in it as Data URLs. The first time you load this page the picture of the elephant is saved in localStorage, and for following page loads the same date, it uses the image stored in localStorage.</p>
                        <p>The second image of the rhino is read through an XMLHttpRequest as an ArrayBuffer, put into a Blob and then read out as a Data URL through a FileReader object.</p>
                        <p>In the <a href="js/base.js">base.js</a> file you can see the code to achieve this.</p>
                        <p>All the <a href="https://github.com/robnyman/robnyman.github.com">code is available at GitHub</a>, for this page and other related demos.
                        </p>
                    </aside>

                    <h2>An elephant, with localStorage</h2>

                    <figure>
                        <img id="elephant" src="about:blank" alt="A close up of an elephant">
                        <noscript>
                            <p><i>You need to have JavaScript enabled to save images in localStorage.</i></p>
                            <img src="elephant.png" alt="">
                        </noscript>    
                        <figcaption>A mighty big elephant, and mighty close too!</figcaption>
                    </figure>

                    
                    <h2>Rhino with XMLHttpRequest and reading file data</h2>
                    <figure>
                        <img id="rhino" src="about:blank" alt="A close up of a rhino">
                        <figcaption>Rhinos are big!</figcaption>
                    </figure>

                </article>
            </div>

            <footer class="page-footer" role="contentinfo">
                Created by <a href="http://robertnyman.com/">Robert Nyman</a><br>
                <a href="https://github.com/robnyman/robnyman.github.com">All demo code at GitHub</a>.
            </footer>

        </div>

        <script src="js/base.js"></script>

    </body>
</html>

c.css 

body {
    font: 12px "Helvetica Neue", "Helvetica", sans-serif;
    background: #ccc;
}

h1 {
    margin-top: 0;
}

img {
    padding: 10px;
    box-shadow: 0 0 10px 2px #ccc;
    margin-bottom: 5px;
}

figcaption {
    font-style: italic;
}

.container {
    width: 900px;
    background: #fff;
    border-radius: 10px;
    margin: 0 auto;
    padding: 30px;
}

header {
    margin-bottom: 20px;
    border-bottom: 1px solid #000;
}

.main-content {
    overflow: hidden;
}

.additional-content {
    float: right;
    width: 300px;
    height: 400px;
    padding: 10px;
    background: #ccc;
    border-radius: 5px
}

.page-footer {
    border-top: 1px solid #000;
    margin-top: 30px;
    padding-top: 10px;
}

参考:https://github.com/robnyman/robnyman.github.com/tree/master/html5demos/localstorage

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值