在这里,我通过 AJAX 传递数组,在控制器中我正在编写一个循环来获取所有值,但只有第一个数组值得到 这是我的响应数组代码,显示在 dd($request->all()) 之后
这是我的控制器代码仅获取第一个数组
$formDataArray = $request->all();
dd($formDataArray);
foreach ($formDataArray as $formData) {
$customInputName = $formData['customInputName'];
$inputType = $formData['inputType'];
$checkedValues = $formData['checkedValues'];
dd($customInputName, $inputType, $checkedValues);
}
我想要所有值,因为我想将每个值插入数据库中。
整个功能代码
// for remove duplicate form
function removeLastElem() {
document.getElementById('customField').lastChild.remove()
}
// function for make copy of form
function duplicateForm() {
var elmnt = document.getElementById("addCustomField");
var cln = elmnt.cloneNode(true);
document.getElementById("customField").appendChild(cln);
}
// for insert data into database
function insertData(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
});
var image = $('#image').prop('files')[0];
var formData = new FormData();
formData.append('eventName', $('#eventName').val());
formData.append('image', image);
formData.append('price',$('#price').val());
formData.append('location',$('#location').val());
formData.append('desc',$('#desc').val());
//custom fields
const forms = document.querySelectorAll('form[name="addCustomField"]');
const formDataArray = [];
forms.forEach((form, index) => {
const customInputName = form.querySelector('[name="customInputName[]"]').value;
const inputType = form.querySelector('[name="inputType[]"]').value;
const checkboxes = form.querySelectorAll('[name="validation[]"]:checked');
const checkedValues = Array.from(checkboxes).map(checkbox => checkbox.value);
formDataArray.push({
customInputName: customInputName,
inputType: inputType,
checkedValues: checkedValues
});
});
$.ajax({
type: 'POST',
dataType: 'json',
url: '{{ url('/inputForm') }}',
data: JSON.stringify(formDataArray),
formData,
contentType: 'application/json',
processData: false,
success: function(response) {
console.log(response);
var successDiv = document.getElementById('successMessage');
successDiv.innerHTML = response.message;
successDiv.classList.add('alert', 'alert-success');
}
});
}
</script> ```
试试这个。
$formDataArray = $request->all();
foreach ($formDataArray as $formData) {
$customInputName = $formData['customInputName'];
$inputType = $formData['inputType'];
$checkedValues = $formData['checkedValues'];
//get checked values from like this array
$checkedValue1 = $checkedValues[0];
$checkedValue2 = $checkedValues[1];
dd($customInputName, $inputType, $checkedValue1, $checkedValue2);
if($customInputName, $inputType, $checkedValue1, $checkedValue2){
//insert here
}
}