javascript - 如何使用保存对话框将表单值保存到 JSON?

标签 javascript jquery html json forms

JS Fiddle将提交表单值,但我希望提交按钮序列化为 JSON 并打开一个保存对话框。它必须离线工作,因此只能使用 HTML 和 JS。

问题

是否存在可以执行此操作的 JQuery 插件?如果不是,我应该研究哪个 JS 函数?

JS

$("#myform").dform({
    "action" : "index.html",
    "method" : "get",
    "html" :
    [
        {
            "type" : "p",
            "html" : "You must login"
        },
        {
            "name" : "username",
            "id" : "txt-username",
            "caption" : "Username",
            "type" : "text",
            "placeholder" : "E.g. user@example.com"
        },
        {
            "name" : "password",
            "caption" : "Password",
            "type" : "password"
        },
        {
            "type" : "submit",
            "value" : "Login"
        }
    ]
});

HTML

<form id="myform"></form>

CSS

body {
    font-family: sans-serif;
    padding: 10px;
}

label, input {
    display: block;
    margin-top: 10px;
}

最佳答案

jQuery 中的 serializeArray() 可以帮助您轻松构建 json:

$("#myform").on('submit', function(e){

    // prevent default submit action
    e.preventDefault();

    var serialized = $(this).serializeArray(),
        obj = {};

    // build key-values
    $.each(serialized, function(){
       obj [this.name] = this.value;
    });

    // and the json string
    var json = JSON.stringify(obj);

    console.log(json);
    // send your data here...

});

对话框是一个更广泛的话题;)

关于javascript - 如何使用保存对话框将表单值保存到 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25978533/

相关文章:

html - 您可以在 CSS 中定义 <col> 标签(带有类)并将它们应用于多个表格吗?

javascript - Firebase Google 登录 token 过期问题

javascript - 将 PHP 变量传递给外部 JavaScript(或 jQuery)文件的最有效方式

javascript - 使用 PySide QtCore.Slot 装饰器的多个参数

javascript - 在 Ajax 响应回调中调用本地 JavaScript 方法

javascript - 通过具有类似数组的属性的属性选择 dom 元素

html - 使用 CSS3 的背景图像底部渐变

html - 如何在 CSS 中实现负填充?

javascript - 在 Meteor 模板标签中串联

javascript - meteor .js : ReferenceError: window is not defined