localStorage在页面刷新后不检索值

bra*_*rad 4 html5

我正在尝试测试html5 localStorage功能.出于某种原因,每当我尝试刷新页面从存储中检索值时,我只返回返回的空值.(如果我尝试在我设置它们的同一个函数中检索值,那么我可以正确地检索它们).

一件事:我正在加载的html/javascript是从本地磁盘请求的(例如,我正在使用字符串:"file:/// C:/testLocalStore.html"来浏览文件,而不是从Web服务器请求它.这会导致我看到的localStore问题吗?

(我想发布完整的代码示例,但我在格式化方面遇到了一些问题.我会很快发布它).

<html> <head> <title>test local storage</title>
<base href="http://docs.jquery.com" />
<script src="http://code.jquery.com/jquery-1.3.js"></script>
<script type="text/javascript">

function savestuff()
    {
        var existingData = localStorage.getItem("existingData");
        if( existingData === undefined || existingData === null )
        {
            // first time saving a map.
            existingData = $("#mapName").val();
        }
        else
        {
            existingData = existingData + "," + $("#mapName").val();
        }

    localStorage.setItem("existingData", existingData);
    // test is non-null here, it was properly retrieved.
    var test = localStorage.getItem("existingData");
}

$(document).ready( function init()
{
    // existing data is always null. 
    var existingData = localStorage.getItem("existingData");
    if( existingData !== null )
    {
        var existingDataListHtml = existingData.split(",");
        existingDataListHtml = $.each(existingData, function(data) {
                return "<li>" + data + "<\/li>";
            });

        $("#existingData").html("<ul>" + existingDataListHtml + "<\/ul>");
    }
} );
</script> 
</head> <body> 
        <form id="loadFromUser" onsubmit="savestuff();">
            <input id="mapName" type="text">
            <input type="submit" value="save">
        </form>
    <div id="existingData"> </div>
</body> </html>
Run Code Online (Sandbox Code Playgroud)

Bri*_*ell 9

是的,在本地加载文件意味着它没有原点.由于localStorage使用同源策略来确定对存储数据的访问,因此未定义当您将其与本地文件一起使用时会发生什么,并且可能不会持久化.

您需要在Web服务器上托管您的文件才能拥有正确的来源; 您可以在本地运行Apache或任何其他服务器并通过它访问它localhost.