使用JavaScript将表单中的动态字段集放入JSON中

时间:2012-12-06 21:49:56

标签: javascript json

我有一个动态行数的表单。每行有3个字段,隐藏ID,代码和交换。

<form id="form_in_question">
    <table>
        <tr>
            <td>0</td>
            <td>
                <input type="hidden" id="id[]" value="123" />
                <input type="input" id="code[]" value="abc" />
            </td>
            <td>
               <select id="exchange[]">
                   <!-- Options... -->
               <select>
            <td>
        <tr>
        <!-- unlimited rows... -->
    </table>
</form>

我想找一个看起来像这样的对象:

data: {
    "0": {
            id: "123",
            code: "abc",
            exchange: "2"
         },
    "1": {
            id: "124",
            code: "bcd",
            exchange: "4"
         }
       }

所以我可以通过AJAX传递一个JSON对象,如:

$("#dialogEditor").dialog('option', 'buttons', {'Save' : function() {
/* Define variables */
var data = $("#form_in_question").serializeArray();
    $.ajax({
    url: 'ajax.codes.php',
    dataType: 'json',
    data: {
        action: "update_codes",
    entryId: entry,
    data: data
    },
                                            type: 'POST',
                                            success: function() {
    ui.showMsg("Codes Updated");
}
});

这就是我实际传递的JSON:

data[0][name]   id[]
data[0][value]  
data[1][name]   code[]
data[1][value]  zxc
data[2][name]   exchange[]
data[2][value]  15
data[3][name]   id[]
data[3][value]  
data[4][name]   code[]
data[4][value]  BVA
data[5][name]   exchange[]
data[5][value]  5

或原始数据:     行动= update_codes&安培; ResortId = 12&安培;数据%5B0%5D%5Bname%5D = ID%5B%5D&安培;数据%5B0%5D%5Bvalue%5D =安培;数据%5B1%5D%5Bname%5D =代码%5B% 5D&安培;数据%5B1%5D%5Bvalue%5D = ZXC&安培;数据%5B2%5D%5Bname%5D =交换%5B%5D&安培;数据%5B2%5D%5Bvalue%5D = 15&安培;数据%5B3%5D%5Bname% 5D = ID%5B%5D&安培;数据%5B3%5D%5Bvalue%5D =安培;数据%5B4%5D%5Bname%5D =代码%5B%5D&安培;数据%5B4%5D%5Bvalue%5D = BVA&安培;数据% 5B5%5D%5Bname%5D =交换%5B%5D&安培;数据%5B5%5D%5Bvalue%5D = 5

我尝试了一种我在SO上找到的方法,但它没有将3个字段组合在一起。

1 个答案:

答案 0 :(得分:0)

以下代码应该有效:

var data = [];
var table = $("table").get()[0];

for (var i=0; i<table.rows.length; i++) {

    var tableRow = table.rows[i];
    var rowData = {};
    var inputData = {};

    inputData["id"] = $("input[id^='id']", $(tableRow.cells[1])).val();
    inputData["code"] = $("input[id^='code']", $(tableRow.cells[1])).val();
    inputData["exchange"] = $("select[id^='exchange']",$(tableRow.cells[2])).val();

    rowData[$(tableRow.cells[0]).text()] = inputData;

    data.push(rowData);
}

console.log(JSON.stringify(data));