我正在开发一个 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"
}]
编辑:固定数据格式:)
关于javascript - 仅使用 JS 或其他客户端库将表单数组元素编码为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38265602/