简体   繁体   English

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

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

Let's assume I have a Form like this: 假设我有一个这样的表格:

<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>

If I submit that form. 如果我提交该表格。 An Array will be submitted that contains the checkboxes (if checked) and the regular input. 将提交一个包含复选框(如果已选中)和常规输入的数组。

Now I want it to either: 现在我想要它:

  • Submit each row as a row in the array 将每一行提交为数组中的一行
  • Only submit the content of the row if the checkbox is checked. 如果选中此复选框,则仅提交该行的内容。

Is there a way to accomplish that? 有没有办法做到这一点?

Edit: 编辑:

Right now I am submitting the Data like this: 现在,我正在提交这样的数据:

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

I'd love to do it with HTML-Markup, if possible. 如果可能的话,我很想用HTML-Markup来做。 As this would be the right way in my opinion. 因为我认为这是正确的方法。

I actually don't want to do some JS/PHP Array juggling. 我实际上不想做一些JS / PHP数组杂耍。 Unless there is a nice way to do it. 除非有一个不错的方法可以做到。 Right now I can only think of some quite ugly foreach stacking. 现在,我只能想到一些非常丑陋的foreach堆栈。

Alright here is how I solved it: 好了,这是我解决的方法:

Leave the form as it is. 保持原样。

Just do some JS Magic. 只需执行一些JS Magic。 Instead submitting the Form I do the following: 代替提交表单,我执行以下操作:

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});

Well it's not the perfect solution I hoped for. 好吧,这不是我希望的完美解决方案。 But it works quite nice. 但是,它的效果很好。 Maybe somebody can come up with a better way to solve it? 也许有人可以想出一种更好的方法来解决它?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM