JavaScript:浏览器的本地存储

cookie、localStorage、sessionStorage的使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>浏览器本地存储</title>
</head>
<body>
    <button onclick="fun1()">cookie存储</button>
    <button onclick="fun2()">cookie获取</button>

    <button onclick="fun3()">localStorage存储</button>
    <button onclick="fun4()">localStorage获取</button>

    <button onclick="fun5()">sessionStorage存储</button>
    <button onclick="fun6()">sessionStorage获取</button>

    <script>
        // 注意:cookie必须运行在服务器环境下,用http协议访问
        function fun1(){
            var dateExpire=new Date();
            dateExpire.setDate(dateExpire.getDate()+1);
            console.log(dateExpire) //cookie的过期时间,设置为1天后过期
            document.cookie="he=哈哈哈;path=/;expires="+dateExpire;
        }
        function fun2(){
            var str=document.cookie;
            console.log(str)
        }

        var hxObj={
            admin:{
                name:'hx',
                age:18
            },
            power:[
                {power_id:1,power_name:'嘎嘎'},
                {power_id:2,power_name:'哈哈'}
            ],
            role:{
                role_id:1,
                role_name:'萨芬'
            }
        }
        //注意:localStorage没有过期时间
        function fun3(){
            localStorage.setItem('he','嘻嘻')
            console.log(JSON.stringify(hxObj))
            localStorage.setItem('hxObj',JSON.stringify(hxObj))
        }
        function fun4(){
            var str=localStorage.getItem('he')
            console.log(str)
            console.log(JSON.parse(localStorage.getItem('hxObj')))
        }

        //注意:sessionStorage关闭浏览器就消失
        function fun5(){
            sessionStorage.setItem('he','哈哈')
        }
        function fun6(){
            var str=sessionStorage.getItem('he')
            console.log(str)
        }
    </script>
    
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/xinhej/p/13376887.html
今日推荐