【问题标题】:own array + jQuery.serializeArray() + post as json自己的数组 + jQuery.serializeArray() + post as json
【发布时间】:2012-06-09 09:06:51
【问题描述】:

我得到数据未定义,我想我不能 ['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()});

有没有更好的方法呢?或者我怎样才能让它工作? 帮助表示赞赏;/

【问题讨论】:

    标签: javascript jquery json serializearray


    【解决方案1】:

    您需要在使用数组和对象之前对其进行初始化。字符串索引仅适用于对象。试试这个:

    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,将表单中的所有内容发布并在服务器上进行整理。

    【讨论】:

    • 嗨!谢谢你的回答!我正在寻找这个!序列化是个好主意,但我不会在我的情况下工作。
    猜你喜欢
    • 2016-01-08
    • 1970-01-01
    • 2017-01-15
    • 2019-05-01
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 2013-03-04
    • 1970-01-01
    相关资源
    最近更新 更多