从表单中获取数据并构建多维数组

Fetch data from form and build a multidimensional array of it

本文关键字:构建 数组 数据 表单 获取      更新时间:2023-09-26

我有一个简单的html表单,其结构如下:

<form name="test" action="">
    <tr class="selectable" data-selected=false>
        <input type="hidden" name="product[gate][id] value=<? echo $pid?>"/>
        <input type="text" name="product[gate][amount]"/> 
    </tr>
</form>

我需要收集每个"数据选择"为true的tr行。

这样,我就可以得到某种数组,然后通过jQueryPOST请求将其发送到服务器。

类似这样的东西:

products => Array(
    [0] => Array(
        id => 1134,
        amount => 2
    ),
    [2] => Array(
        id => 1134,
        amount => 3
    )
)

我不知道如何用js构建多维数组,我也不熟悉js对象或JSON。最简单的方法是什么?

试试这个:

var $trs = $("tr").filter(function() {
    return $(this).data("selected");
});
var products = [];
$.each($trs, function(i, $tr) {
    products.push({
        "id": $('input[type="hidden"]', $tr).val(),
        "amount": $('input[type="text"]', $tr).val()
    });
})

小提琴示例

products变量的格式应该可以在AJAX调用中使用。您可能希望在工作代码中使用比input[attr](例如一个类)更好的选择器。

我假设表单标记中有必要的数据。如果你不想发布任何数据,那么它不应该在<form>中。

$('form').submit(function() {
  alert($(this).serialize());
  return false;
});

更多信息:http://api.jquery.com/serialize/