2012-06-09 27 views
1

我得到的數據是不確定的,我想我不能['productId']在數組中,但我想我需要這個結構在JSON中,我試過了幾個變化,但它從來沒有,我需要 我只是想通過ajax發送一個json。自己的數組+ jQuery.serializeArray()+發佈爲json

jQuery(':checked').each(function(i){ 
    data[i]['productId'] = jQuery(this).parent().find('.productId').val(); 
    jQuery(this).parent().find('.attrGrp').each(function(j){ 
    data[i]['attrGrps'][j]['uid'] = jQuery(this).find('.active').attr('id'); 
    data[i]['attrGrps'][j]['amount'] = jQuery(this).parent().find('.amount').val(); 
    }); 
}); 
jQuery.post(newSession, {json: data.serializeArray()}); 

有沒有更好的方法來做到這一點?或者我如何使它工作? 幫助讚賞;/

回答

0

您需要在使用它們之前初始化數組和對象。字符串索引只能用於對象。試試這個:

var data = []; 
jQuery(':checked').each(function(i) 
{ 
    data[i] = {}; 
    data[i].productId = jQuery(this).parent().find('.productId').val(); 
    data[i].attrGrps = []; 
    jQuery(this).parent().find('.attrGrp').each(function(j) 
    { 
    data[i].attrGrps[j] = {}; 
    data[i].attrGrps[j].uid = jQuery(this).find('.active').attr('id'); 
    data[i].attrGrps[j].amount = jQuery(this).parent().find('.amount').val(); 
    }); 
}); 

另外,你可以使用jQuery().serialize,在窗體中發佈一切,並在服務器上進行排序。

+0

嗨!謝謝你的答案!我正在尋找這個!序列化是一個好主意,但我不會在我的情況下工作。 – dni