Laravel中通过AJAX提交多份重复表单数据并存入数据库
实现多表单批量AJAX提交方案
原代码依赖ID选择器,表单复制后ID重复,无法正确获取每个表单的输入值。要实现批量提交,按以下步骤修改:
1. 修正表单结构(改用类选择器)
把原表单的ID替换成类,避免重复ID的问题:
<form action="" method="POST" enctype="multipart/form-data" class="custom-field-form"> <input type="text" class="form-control custom-input-name" required name="customInputName" placeholder="Pool Party" aria-label="Pool Party" > <div class="col-md-10"> <div class="form-check mb-2"> <input class="form-check-input" type="checkbox" value="required" name="validation[]" checked /> <label class="form-check-label" for="required">Required</label> </div> <div class="form-check mb-2"> <input class="form-check-input" type="checkbox" value="alpha" name="validation[]" /> <label class="form-check-label" for="alpha">Alphabets Only</label> </div> <div class="form-check mb-2"> <input class="form-check-input" type="checkbox" value="/^[a-zA-Z\s]+$/" name="validation[]" /> <label class="form-check-label" for="alphaSpace">Alphabets with Space</label> </div> <div class="form-check mb-2"> <input class="form-check-input" type="checkbox" value="number" name="validation[]" /> <label class="form-check-label" for="number">Number Only</label> </div> </div> </form>
注:移除了表单和输入框的ID,改用类名;如果需要label关联,可以给每个复选框生成动态ID,批量提交时类选择器足够满足需求。
2. 改进表单复制函数
克隆表单后移除ID、清空输入内容,避免重复数据和ID冲突:
function duplicateForm() { const originalForm = document.querySelector('.custom-field-form'); const clonedForm = originalForm.cloneNode(true); // 移除克隆表单的ID(避免重复) clonedForm.removeAttribute('id'); // 清空克隆表单的输入值 clonedForm.querySelectorAll('input').forEach(input => { if (input.type === 'text') input.value = ''; if (input.type === 'checkbox') input.checked = false; }); // 保持默认选中第一个复选框(和原表单一致) clonedForm.querySelector('input[type="checkbox"][value="required"]').checked = true; document.getElementById('customField').appendChild(clonedForm); }
3. 重写批量提交的AJAX函数
遍历所有表单,收集每个表单的数据,打包成数组后提交:
function submitAllForms() { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}' } }); const allFormData = []; // 遍历每个表单,收集数据 document.querySelectorAll('.custom-field-form').forEach(form => { const formDataObj = {}; // 获取文本输入框值 formDataObj.customInputName = form.querySelector('.custom-input-name').value; // 获取inputType值(假设你有对应的下拉框,需改用类选择器) formDataObj.inputType = form.querySelector('.input-type').value; // 获取选中的复选框值 const checkedBoxes = form.querySelectorAll('input[type="checkbox"]:checked'); formDataObj.validation = Array.from(checkedBoxes).map(box => box.value); allFormData.push(formDataObj); }); $.ajax({ type: 'POST', dataType: 'json', url: '{{ url('/inputForm') }}', data: JSON.stringify(allFormData), contentType: 'application/json', // 提交JSON格式数据 success: function(response) { console.log(response); const successDiv = document.getElementById('successMessage'); successDiv.innerHTML = response.message; successDiv.classList.add('alert', 'alert-success'); }, error: function(xhr) { console.error(xhr.responseText); // 可添加错误提示逻辑 } }); }
后端接收示例(以Laravel为例)
后端需要接收JSON数组,逐个处理表单数据:
public function store(Request $request) { $formDataArray = $request->json()->all(); foreach ($formDataArray as $formData) { // 验证单个表单数据 $validated = validator($formData, [ 'customInputName' => 'required|string', 'inputType' => 'required|string', 'validation' => 'array' ])->validate(); // 执行保存逻辑,例如写入数据库 // CustomField::create($validated); } return response()->json(['message' => '所有表单数据提交成功']); }
内容的提问来源于stack exchange,提问作者Meera
相关产品推荐
相关产品推荐

