首页 > 解决方案 > 我如何在 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。我有不同的表/objectStorestockform

标签: javascriptjqueryarrays

解决方案


尝试这个..

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>


推荐阅读