0

我有一个具有动态行数的表单。每行有 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

或原始数据:action=update_codes&ResortId=12&data%5B0%5D%5Bname%5D=id%5B%5D&data%5B0%5D%5Bvalue%5D=&data%5B1%5D%5Bname%5D=code%5B%5D&data%5B1 %5D%5Bvalue%5D=zxc&data%5B2%5D%5Bname%5D=exchange%5B%5D&data%5B2%5D%5Bvalue%5D=15&data%5B3%5D%5Bname%5D=id%5B%5D&data%5B3%5D %5Bvalue%5D=&data%5B4%5D%5Bname%5D=code%5B%5D&data%5B4%5D%5Bvalue%5D=BVA&data%5B5%5D%5Bname%5D=exchange%5B%5D&data%5B5%5D%5Bvalue %5D=5

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

4

1 回答 1

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));
于 2012-12-06T23:28:08.327 回答