0

我正在尝试将表单数据序列化为 JSON 对象,但是当我需要创建购物车对象时遇到了困难。

获取表单中的所有数据后,我想要实现的是一个像下面的代码片段一样的对象。我怎样才能做到这一点?

所以你可以在这里查看和测试完整的代码http://jsbin.com/OyAzAZA/3/

{
  "client_id": 1,
  "carts": [
    {
      "cart_id": 1,
      "items": [
        {
          "code": "01",
          "descrption": "text 1"
        },
        {
          "code": "02",
          "descrption": "text 2"
        }
      ]
    },
    {
      "cart_id": 2,
      "items": [
        {
          "code": "03",
          "descrption": "text 3"
        },
        {
          "code": "04",
          "descrption": "text 4"
        }
      ]
    }
  ]
}
4

1 回答 1

0

这是获取指定 JSON 的代码:

$(function() {
    $('form').on('click', 'button', function() {
        var clientId = $('form').find('input[name="client_id"]').val(),
        $tables = $('form').find('table'),
        data = {};

        data.client_id = clientId;
        data.carts = [];

        $.each($tables, function(i, v) {
            var cart = {};
            cart.cart_id = $(v).attr('id');
            cart.items = [];
                $rows = $(v).find('tr');

            $.each($rows, function(i, v) {
              var item = {};
                item.code = $(v).find('input[name="code"]').val();
                    item.description = $(v).find('input[name="description"]').val();
              cart.items.push(item);
            });
          data.carts.push(cart);
        });
    console.log(data);
});
});
于 2013-09-11T22:40:18.970 回答