仅使用JS或其他客户端库将表单数组元素编码为JSON

时间:2016-07-08 11:33:50

标签: javascript jquery json serialization

我正在处理一个joomla组件而且它没有像我需要的那样处理表单数据的序列化,所以我的解决方案是创建一个隐藏的textarea并用创建的json数据填充它。表单在客户端填写,然后只提交文本区域。

  <input type="text" name="jform[work_experience][]employer"><input type="text" name="jform[work_experience][]position"><br/>
  <input type="text" name="jform[work_experience][]employer"><input type="text" name="jform[work_experience][]position"><br/>
  <input type="text" name="jform[work_experience][]employer"><input type="text" name="jform[work_experience][]position"><br/>

想象一下,我的表单看起来就是这样的&#34;行数&#34;是动态的,取决于用户需要多少。然后我想将其序列化为一个类似于:

的JSON字符串
[
  {
    "employer": "apple",
    "position": "contract killer"
  },
  {
    "employer": "microsoft",
    "position": "bathroom attendant"
  },
  {
    "employer": "samsung",
    "position": "window washer"
  }
]

如果我需要重命名字段以获得正确的结构,那就这样吧。

是否有一个jQuery函数可以让我jform[work_experience]并吐出一个json字符串?

1 个答案:

答案 0 :(得分:1)

在这里,我添加数据类型以更轻松地选择内容。它使用原生JS,所以你不必担心与框架或库的冲突。我还假设这些领域是串联的。

<form id="uniqueId">
    <input type="text" name="jform[work_experience][]employer" data-type="employer" value="apple">
    <input type="text" name="jform[work_experience][]position" data-type="position" value="contract killer"><br/>

    <input type="text" name="jform[work_experience][]employer" data-type="employer" value="apples">
    <input type="text" name="jform[work_experience][]position" data-type="position" value="Designer"><br/>

    <input type="text" name="jform[work_experience][]employer" data-type="employer" value="appe">
    <input type="text" name="jform[work_experience][]position" data-type="position" value="Sales rep"><br/>

</form>

JS:

var inputFields = document.querySelectorAll( '#uniqueId input' );
var dataObject = [];
for( var x = 0 ; x < inputFields.length ; x++ ){
    if( inputFields[ x ].dataset.type === "employer" ){
        var current = {};
        current.employer = inputFields[ x ].value;
        current.position = inputFields[ x + 1 ].value;
        dataObject.push( current );
        x++;    //skip check for next input
    }
}
//verify that the object holds data. The loop assumes 
//that employer and position come in tandem
console.log( JSON.stringify( dataObject ));

输出:

[{
        "employer": "apple",
        "position": "contract killer"
}, {
        "employer": "apples",
        "position": "Designer"
}, {
        "employer": "appe",
        "position": "Sales rep"
}]

编辑:修正了数据格式:)