仅使用 JS 或其他客户端库将表单数组元素编码为 JSON
Encode form array elements into JSON using only JS or other client side libs
我正在处理一个 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"
}]
编辑:修复了数据格式:)
相关文章:
- 在函数中添加数组元素的数值
- 访问JSON对象内部的数组元素
- Mongoose-在更新中删除数组元素
- javascript数组元素是否知道其封闭数组
- 将数组元素附加到FormData dos'不适用于Firefox 15
- 如何在javascript中使用click函数选择数组元素
- 如何在JavaScript中剥离数组元素中的非整数
- 消隐数组元素是否生成自己的属性
- 如何使用Jquery水平打印表中的数组元素,并在某个元素之后垂直打印
- 如何在 javascript 中将表单中的元素 id 值作为数组传递
- Javascript:如果数组元素已填充,则为数组的每个元素插入表行
- JSON数组元素作为单个数组
- 显示按表单构建的数组的数组元素总数
- 推送到附加了单引号的数组元素
- 如何在YII2中单击按钮后获得表的数组
- 在单击值数组元素时从该元素访问数据
- 如何用数组元素作为按钮的标签动态创建单选按钮
- 数据表中数组元素的表示
- 如何使用单选按钮连接数组元素
- 单击以获取数组元素的jquery索引