我得到的数据是未定义的,我想我不能在数组中['productId'],但我认为我需要json中的这个结构,我尝试了一些变体,但从来没有,我需要什么 我只想通过ajax发送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()});
有没有更好的办法?或者我怎样才能让它发挥作用? 帮助表示感谢;/
最佳答案
使用数组和对象之前需要先初始化它们。字符串索引只能用于对象。试试这个:
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 ,将表单中的所有内容发布并在服务器上进行整理。
关于javascript - 自己的数组 + jQuery.serializeArray() + 作为 json 发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10959726/