将表单数据序列化为 JSON 对象
Serialize form data into JSON object
我正在尝试将表单数据序列化为 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);
});
});
相关文章:
- jQuery匹配JSON对象的部分文本
- 如何在Javascript中将JSon对象转换为数组
- 我可以在json对象中添加一个函数吗
- 使用JS将数组转换为json对象
- 如何为json对象中的段发送array[]
- 将JSON对象传递给angular指令
- 更改JSON对象的结构
- 访问JSON对象内部的数组元素
- 在ejs-partial中对JSON对象进行迭代
- 遍历 JSON 对象并检查 URL 是否以某个值结尾
- 访问嵌套JSON对象的键,其中键是动态的
- json对象中缺少对象循环
- 发送json对象或使用express路由呈现视图
- 在play2框架中向json对象添加下拉列表项
- 元素名称上带有短划线 (-) 字符的 Json 对象
- autocomplete不接受源的json对象
- 如何在javascript中创建动态json对象
- 在使用客户端脚本时拾取JSON对象
- 如何通过json对象数组为嵌套对象赋值
- 构造JSON对象