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

Serialize form data into JSON object

本文关键字:JSON 对象 序列化 表单 数据      更新时间:2023-09-26

我正在尝试将表单数据序列化为 JSON 对象,但是当我需要创建 carts 对象时,我卡住了。

在获取表单中的所有数据后,我想要实现的是一个对象,如下面的代码片段所示。我该怎么做?

因此,您可以在此处查看和测试完整的代码 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);
});
});