javascript - 我如何在 js 中将提交的表单(输入如 name="array[key]")类型数据作为数组/对象在提交回调中使用
问题描述
我有表单,我在其中提交多个输入,其中包含名称属性作为数组,例如name="array[key]"
<form onsubmit="callback($(this));">
<input type="text" name="stock[quantity]">
<input type="text" name="stock[old]">
<input type="text" name="form[mrp]">
<input type="text" name="form[price]">
</form>
我尝试过 newformData($("form")[0])
和 jQuery$("form").serializeArray()
都name="array[key]"
以字符串形式返回。
我希望这些数据作为多维对象,就像我们在提交此表单时在 php 中得到的一样。
<script>
function callback($form){
/*
here i want form data in js object like
{
stock : {quantity : ... , old : ....},
form : {mrp : ... , price : ....}
}
or something like this
*/
}
</script>
我在这个项目中使用 JS、jQuery 和 Vue.js,实际上我想在服务器上成功保存后将此表单数据放入 indexedDB。我有不同的表/objectStore
stock
和form
解决方案
尝试这个..
function callback($form) {
let result = {};
let formData = $form.serializeArray();
formData.forEach(obj => {
let inputValue = obj.name.split('[');
if (!result[inputValue[0]]) {
result[inputValue[0]] = {};
}
let innerText = inputValue[1].replace(']','');
result[inputValue[0]][innerText] = obj.value;
});
console.log(result);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onsubmit="callback($(this)); return false;">
<input type="text" name="stock[quantity]">
<input type="text" name="stock[old]">
<input type="text" name="form[mrp]">
<input type="text" name="form[price]">
<input type="submit" value="submit">
</form>
推荐阅读
- css - SVG异常旋转不固定
- c# - ListBox SelectedIndex 作为命令参数
- java - 当日期为夏令时时,GregorianCalendar.getTime() 默认时间不同
- javascript - 页面刷新后不会进行提取
- php - 如何检查是否从laravel新页面的其他页面中选择了选择选项
- nlp - 是否可以在 WordNet 数据集上获取类?
- java - 使用rabbitmq的Spring boot Failover retryer:无法调用目标方法
- facebook-graph-api - 为什么收到应用请求限制达到#4?
- javascript - 如何将 API 调用从工作的浏览器端网站移至服务器端?
- javascript - 在 JavaScript 中使用 C# 格式字符串