如何构造/控制表单提交的数据


How to structure/control the data that was submitted by a Form?

让我们假设我有一个这样的表单:

<form>
    <table>
        <thead>
        <th>
            Submit?
        </th>
        <th>
            Data
        </th>
        </thead>
        <tbody>
            <tr>
                <td>
                    <input type="checkbox" name="c1">
                </td>
                <td>
                    <input name="t1">
                </td>
            </tr>
            <tr>
                <td>
                    <input type="checkbox" name="c2">
                </td>
                <td>
                    <input name="t2">
                </td>
            </tr>
        </tbody>
    </table>
</form>

如果我提交该表单。将提交一个数组,其中包含复选框(如果选中)和常规输入。

现在我想让它:

  • 将每一行作为数组中的一行提交
  • 只有选中复选框时才提交行的内容

有办法做到这一点吗?

编辑:

现在我正在提交这样的数据:

$.post(url, { attributes: $(form).serializeArray() })

如果可能的话,我很乐意使用HTML标记。因为在我看来这是正确的方式。

实际上,我不想做一些JS/PHP数组杂耍。除非有一个好的方法。现在我只能想到一些非常丑陋的前臂堆叠。

好吧,下面是我解决它的方法:

保持表格原样。

只是做一些JS魔术。相反,我会提交以下表格:

var submitData = {};
$("input:checked.attributCheckbox").each(function() {
    var id = $(this).attr('name');
    // This is how I get the input for the checkbox.
    var val = $("input[type=number][name="+ id +"]").val();
    submitData[id] = val;
});
$.post(url, {attributes : submitData});

这不是我所希望的完美解决方案。但效果很好。也许有人能想出一个更好的方法来解决它?