此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;
}
答案 0 :(得分:4)
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...
});
对话框是一个更广泛的主题;)