繁体   English   中英

将表单数据序列化为JSON对象

[英]Serialize form data into JSON object

我正在尝试将表单数据序列化为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"
        }
      ]
    }
  ]
}

这是获取指定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);
});
});

暂无
暂无

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

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