【问题标题】:Convert Multidimentional Input arry to JSON将多维输入数组转换为 JSON
【发布时间】:2013-04-17 19:34:48
【问题描述】:

我想最终获取我的输入字段 value 并将它们放入 JSON 字符串中(通过 Jquery/Javascript)。

这是我的 html 标记

<input type="text" class="specifications" name="specifications[0][title]" />
<input type="text" class="specifications" name="specifications[0][stat]" />

<input type="text" class="specifications" name="specifications[1][title]" />
<input type="text" class="specifications" name="specifications[1][stat]" />

<input type="text" class="specifications" name="specifications[2][title]" />
<input type="text" class="specifications" name="specifications[2][stat]" />

<input type="text" class="specifications" name="specifications[3][title]" />
<input type="text" class="specifications" name="specifications[3][stat]" />

我希望我的 JSON 字符串是这样的

[
{ title: 'title1', stat: '1000' },
{ title: 'title1', stat: '2000' },
{ title: 'title2', stat: '3000' },
{ title: 'title3', stat: '4000' },
{ title: 'title4', stat: '5000' }
]

我现在搜索了很多并找到了这些线程,但它们并没有帮助我完成我想要完成的任务

jquery serialize input with arrays

Submit form input array with jquery ajax post

请帮忙。

【问题讨论】:

  • 那不是 JSON,那是一个 JavaScript 对象。
  • 之后你打算如何处理对象(或 JSON 字符串)?

标签: javascript jquery json multidimensional-array


【解决方案1】:

这将根据您的输入创建您描述的对象:

    var specsLen = $('input.specifications').length / 2,
        array = [],
        i;
    for (i = 0; i < specsLen; i += 1) {
        array.push({
            title: $('input.specifications[name="specifications[' + i + '][title]"]').val(),
            stat: $('input.specifications[name="specifications[' + i + '][stat]"]').val()
        });
    })

See fiddle example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多