2013-05-06 48 views
1

我有一個表格看起來有點像這樣窗體上使用serializeObject()來創建一個JSON對象與內部陣列

<form> 
<input type='text' name='_id'/> 
<input type='text' name='name'/> 
<textarea name='description'/> 
<input type='text' name='category'/> 
<input type='checkbox' name='reservable'/> 
<ol> 
    <li><input type ='text' name='_id'/><input type='text' name='name'/><input type='text' name='value'/></li> 
    <li><input type ='text' name='_id'/><input type='text' name='name'/><input type='text' name='value'/></li> 
</ol> 
</form> 

我試圖使用serializeObject()方法,此表上的它在大多數情況下運作良好。問題是我想要的清單裏面的元素製成,每個li元素,像這樣的數組中的對象的數組..

{ 
_id:'5', 
name:'bob', 
description:'tall', 
categoryId:'human', 
reservable:'false', 
attributes: 
[ 
    { 
     _id:'3', 
     name:'hair', 
     value:'brown' 
    } 
] 

}

什麼,現在我得到像這樣

{ 
"_id:":"5", 
"name:":"bob", 
"description:":"tall", 
"categoryId":"human", 
"name":["hair",""], 
"value":["brown",""] 
} 

有沒有一種方法,我可以讓它使屬性的對象數組?此外,如果有人可以告訴我爲什麼我的複選框沒有顯示,我將不勝感激。

+0

未選中的複選框沒有任何價值,因此絕不會出現。 你可以把你現有的結果和映射/減少它到你期望的結果,填寫任何缺失值的默認值。 – ChrisF 2013-05-06 03:32:17

回答

2

我這樣做沒有測試,所以希望我不會失敗,並可以推動你在正確的方向。我想嘗試一些與此類似:

HTML

<form> 
<input type='text' name='_id' id="the_id"/> 
<input type='text' name='name' id="the_name"/> 
<textarea name='description' id="desc"/> 
<input type='text' name='category id='category'/> 
<input type='checkbox' name='reservable' id='reservable' /> 
<ol> 
    <li><input type ='text' name='_id'/><input type='text' name='name' id='attr_part' /><input type='text' name='value'/></li> 
    <li><input type ='text' name='_id'/><input type='text' name='name id='attr_color'/><input type='text' name='value'/></li> 
</ol> 
</form> 

jQuery的

// Initializes the array 
var person = {}; 

person.id = $('#the_id').val(); 
person.name = $('#the_name').val(); 
person.desc = $('#desc').text(); 
person.category = $('#category').val(); 
person.reservable = $('#reservable').val(); 

// Initialize the attributes array 
person.attributes = {}; 

var attribute = {}; 

attribute.part = $('#attr_part').val(); 
attribute.color = $('#attr_color').val(); 

person.attributes.push(attribute); 
相關問題