说一下前端数据存储方式(cookies,localstorage,sessionstorage,indexedDB)的区别?

说一下前端数据存储方式(cookies,localstorage,sessionstorage,indexedDB)的区别?,第1张

Cookie最初是在客户端用于存储会话信息的,其要求服务器对任意HTTP请求发送Set-CookieHTTP头作为响应的一部分。cookie

以name为名称,以value为值,名和值在传送时都必须是URL编码的。浏览器会存储这样的会话信息,在这之后,通过为每个请求添加Cookie

HTTP头将信息发送回服务器。

localstorage

存储方式

以键值对(Key-Value)的方式存储,永久存储,永不失效,除非手动删除。

sessionstorage

HTML5 的本地存储 API 中的 localStorage 与 sessionStorage 在使用方法上是相同的,区别在于 sessionStorage 在关闭页面后即被清空,而 localStorage 则会一直保存。

IndexedDB

索引数据库(IndexedDB) API(作为 HTML5 的一部分)对创建具有丰富本地存储数据的数据密集型的离线 HTML5 Web 应用程序很有用。同时它还有助于本地缓存数据,使传统在线 Web 应用程序(比如移动 Web 应用程序)能够更快地运行和响应。

使用cookie即可。

<!DOCTYPE HTML>

<html lang="en-US">

<head>

<meta charset="UTF-8">

<meta name="keywords" content="白菜编辑部">

<title>白菜编辑部</title>

<style type="text/css">

</style>

<script type="text/javascript">

    function readCookie (name)

    {

        var cookieValue = ""

        var search = name + "="

        if (document.cookie.length > 0)

        {

            offset = document.cookie.indexOf (search)

            if (offset != -1)

            {

                offset += search.length

                end = document.cookie.indexOf ("", offset)

                if (end == -1)

                    end = document.cookie.length

                cookieValue = unescape (document.cookie.substring (offset, end))

            }

        }

        return cookieValue

    }

    function writeCookie (name, value, hours)

    {

        var expire = ""

        if (hours != null)

        {

            expire = new Date ((new Date ()).getTime () + hours * 3600000)

            expire = " expires=" + expire.toGMTString ()

        }

        document.cookie = name + "=" + escape (value) + expire

    }

     

    writeCookie ("myCookie", "my name", 24)

    alert (readCookie ("myCookie"))

</script>

</head>

<body>

</body>

</html>


欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/sjk/9980039.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-04
下一篇 2023-05-04

发表评论

登录后才能评论

评论列表(0条)

保存