正确地将表单序列化为json

时间:2014-04-01 13:11:23

标签: javascript jquery json serialization

我如何序列化这样的表格:

<form id="SomeForm">
    <input type="hidden" name="testId" value="123" />

    <input type="radio" name="question-1" value="1" />
    <input type="radio" name="question-1" value="2" />
    <input type="radio" name="question-1" value="3" />

    <input type="radio" name="question-2" value="1" />
    <input type="radio" name="question-2" value="2" />
    <input type="radio" name="question-2" value="3" />
    <input type="radio" name="question-2" value="4" />
</form>

这样的JSON结构:

{ 
"testid" : 123,
"questions" : [   
    { "question" : [ {
        "id" : 1,
        "answer" : 2
    }]},
    { "question" : [ {
        "id" : 2,
        "answer" : 4
    }]}
]
} 

2 个答案:

答案 0 :(得分:0)

var form = $('#SomeForm').serializeArray();
var formObject = {};
$.each(form ,
    function(i, v) {
        formObject[v.name] = v.value;
    });

了解更多信息: -

http://css-tricks.com/snippets/jquery/serialize-form-to-json/

答案 1 :(得分:0)

试试这个:

$(document).ready(function(){
var frm = $("#SomeForm");
var data = JSON.stringify(frm.serializeArray());
console.log(data);

$("#test").click(function(){
    var frm = $("#SomeForm");
    var data = JSON.stringify(frm.serializeArray());
    alert(data);
});
});

工作小提琴:http://jsfiddle.net/robertrozas/as55D/