将数据保存到本地存储中的json文件中

时间:2015-07-31 14:59:48

标签: javascript json html5 backbone.js local-storage

我在Backbone上开发了HTML5游戏。当您想使用编辑菜单并编辑世界时,它使用本地存储。您也可以使用此菜单更改角色。所以我想在游戏开始之前添加角色选择,但我真的不知道如何将其插入到文件中。 文件看起来像这样:

3:"{"viewportBottom":0,"id":3,"tiles":[],"x":0,"y":0,"tileWidth":32,"tileHeight":32,"width":212,"height":17,"backgroundColor":"rgba(66, 66, 255, 1)","name":"level_1-1","sprites":[
{"name":"ground-ug","state":"idle","sequenceIndex":0,"x":32,"y":512},
{"name":"ground-ug","state":"idle","sequenceIndex":0,"x":0,"y":512},
{"name":"ground-ug","state":"idle","sequenceIndex":0,"x":64,"y":512},
{"name":"ground-ug","state":"idle","sequenceIndex":0,"x":128,"y":512},
{"name":"luigi","state":"idle-right","sequenceIndex":0,"x":192,"y":448,"velocity":0,"acceleration":0,"yVelocity":0,"yAcceleration":0}
],"savedOn":"2015-07-31T14:29:08.725Z","state":"play","viewportTop":0,"viewportRight":0,"viewportLeft":0,"time":748}"

例如,我想将Luigi改为Mario,但我真的很不喜欢。

        <p id="Character" onclick="choose('mario')">Mario</p>

        <script>

            var character;
function choose(choice){
    character = choice;
}


            var parsed = JSON.parse(myJSONData, function(k, v) {
                    if (v === "mario") 
                        this.value = character;
                    else
                        return v;
                });
    }
        </script> 

顺便说一下它不能正常工作:D我也不知道如何将它存储到本地存储中。我正在查看文档,而且我没那么聪明:D 这款基于Backbone的游戏的文档:http://martindrapeau.github.io/backbone-game-engine/

请问有人帮帮我吗? :)谢谢。

1 个答案:

答案 0 :(得分:1)

将内容存储到本地存储:

localStorage.variableName = 'value';

请注意,本地存储只允许您使用strings,因此存储JSON数据意味着执行JSON.stringify(data)

从本地存储中检索非常简单:

var dataStr = localStorage.variableName;