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

Encode form array elements into JSON using only JS or other client side libs

本文关键字:表单 数组元素 编码 JSON 客户端 JS 其他      更新时间:2023-09-26

我正在处理一个 joomla 组件,它没有按照我需要的方式处理我的表单数据的序列化,所以我的解决方案将是创建一个隐藏的文本区域,并使用在客户端填写表单时创建的 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/>

想象一下,我的表单看起来像这样,其中"行"的数量是动态的,具体取决于用户需要多少。然后我想将其序列化为一个 JSON 字符串,如下所示:

[
  {
    "employer": "apple",
    "position": "contract killer"
  },
  {
    "employer": "microsoft",
    "position": "bathroom attendant"
  },
  {
    "employer": "samsung",
    "position": "window washer"
  }
]

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

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

在这里,我添加了数据类型以更轻松地选择内容。它使用本机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"
}]

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