[英]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.