这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/