JSON.stringify是否考虑了section / parent divs?

时间:2013-07-24 14:07:18

标签: jquery json

HTML表单分为几个部分。章节有他们的输入字段。当我以JSON格式发送表单数据时,就像下面给出的代码一样。控制器接收表格数据作为一维数组 有没有办法将表单数据作为二维数组发送?其中section-name将包含字段的名称/值对数组。

$('form').submit(function () {
                    alert('here');
                    $.ajax({
                        url: $(this).attr('action'),
                        type: 'POST',
                        data: JSON.stringify($(this).serializeArray()),
                        contentType: 'application/json',
                        success: function (data) {
                            alert('data')
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            alert('An error has occured!! :-(')
                        }
                    });

                    return false;
                })
            });

1 个答案:

答案 0 :(得分:1)

有,但你不能用.serializeArray()来做;你需要使用jQuery遍历DOM,将数据组合成一个格式化的数组格式,然后将其作为data参数的值传递给.ajax()。考虑以下设计的例子:

<form>

  <div class="section">
    <span class="section_title">Section 1</span>
    <input name="this" type="text" value="this" />
    <input name="that" type="text" value="is" />
  </div>

  <div class="section">
    <span class="section_title">Section 2</span>
    <input name="these" type="text" value="rather" />
    <input name="those" type="text" value="contrived" />
  </div>

</form>

您可以使用以下Javascript代码进行操作:

var formdata = {};
$('form').find('div.section')
    .each(function(i, el) {
        var sectionTitle = $(el)
            .find('span.section_title')
            .text();
        $(el).find('input')
            .each(function(i, el) {
                var name  = $(el).attr('name');
                var value = $(el).val();
                formdata[sectionTitle][name] = [value];
            });
    });

结果,在formdata中,将是:

{'Section 1': {'this': 'this',
               'that': 'is'},
 'Section 2': {'these': 'rather',
               'those': 'contrived'}}

当然,它不是为你的情况量身定制的,但它应该足够接近你的想法;如果没有,请随意评论要求澄清,我会尽力提供。 (顺便提一下,在您的问题中显示您正在使用的表单的HTML示例,可以提供更适合您情况的解决方案。)

相关问题