【问题标题】:How to store form value as json array to localstorage如何将表单值作为json数组存储到localstorage
【发布时间】:2018-02-11 10:14:03
【问题描述】:

我正在尝试将表单数据作为 json 数组附加到 localstorage 中,但它不起作用。

这是我的表格

<form>
<label>Choose a option</label>
<input type="radio" name="icon" value="icon1.png">
<input type="radio" name="icon" value="icon2.png">
<input type="radio" name="icon" value="icon3.png">

<label>Name</label>
<input type="text" name="name" placeholder="Your Name">

<button type="submit" id="save">Save</button>
</form>   

这是我要保存的内容。

{
    "info": [
        {
            "name": "John",
            "icon": "icon1.png"
        },
        {
            "name": "Daniel",
            "icon": "icon2.png"
        }
    ]
}

我的尝试

$("form").submit(function(e) {
    e.preventDefault();
    // serialize `form`
    var values = $(this).serializeArray();
    values.push(function(item, index) {
        $("#test").append(item.name + " " + item.value + "<br>");
    })

    localStorage.setItem("jsonFav", JSON.stringify(values))
})

【问题讨论】:

  • 你尝试了什么?
  • 您能否将其包含在您的帖子中而不是在评论中。

标签: javascript jquery html json local-storage


【解决方案1】:

var results=localStorage.getItem("json") || {info: []};
$(window).submit(function(evt) {

evt.preventDefault();

results["info"].push({
name: $('input[name=name]').val(), 
icon: $('input[name=icon]:checked').val()
});

localStorage.setItem("json", results);

});
// To get json as string use JSON.stringify(jsonValue);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label>Choose a option: </label>
<input type="radio" name="icon" value="icon1.png">
<input type="radio" name="icon" value="icon2.png">
<input type="radio" name="icon" value="icon3.png"><br>

<label>Name:</label>
<input type="text" name="name" placeholder="Your Name"><br>

<button type="submit" id="save">Save</button>
</form>

【讨论】:

  • 谢谢!这行得通!但每次我重新加载页面并提交时它都会替换本地存储
  • 谢谢@MBJH!它可以工作,但需要一些修改。如果 localstorage 在 .clear() 之后没有 json 的 key,新的结果将不会被推送。
【解决方案2】:

这是你应该做的事情

var yourObject = {
    "info": [{
        "name": "John",
        "icon": "icon1.png"
     },{
        "name": "Daniel",
        "icon": "icon2.png"
     }]
}

localStorage.setItem('yourObject', JSON.stringify(yourObject));

它将给定的json存储在localstorage中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 2012-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    相关资源
    最近更新 更多