【发布时间】:2021-09-05 05:31:38
【问题描述】:
撇开可怕的标题不谈,我目前有一个动态表单,其中包含任务和每个任务的状态。任务的数量和状态可能会有所不同。我要做的是提交与该状态相关的任务名称、状态名称和颜色。
<form>
<div class='task'>
<input type="text" name="taskName[]" value="Task name">
<input type="text" name="status[]" class="pill gray" value="Status name">
<input type="text" name="status[]" class="pill blue" value="Status Name">
<input type="text" name="status[]" class="pill orange" value="Status Name">
<button>Add Status</button>
</div>
<div class='task'>
<input type="text" name="taskName[]" value="Task name">
<input type="text" name="status[]" class="pill red" value="Status name">
<input type="text" name="status[]" class="pill yellow" value="Status Name">
<button>Add Status</button>
</div>
<button>Add Task</button>
</form>
我通过 js 提交表单,唯一不同的是从颜色创建一个数组。
let colors = [];
for (let i = 0; i < tasks.length; i++) {
const element = statuses[i];
let pills = element.querySelectorAll('.pill');
pills.forEach(element => {
colors.push([element.classList[1]]);
});
}
// Submit form
formData = new FormData(form);
formData.append("colors", colors);
// Ajax to php
在 php 页面上,我可以遍历任务,但我不确定如何遍历与该任务相关的状态。目前每个任务都显示所有状态。
$taskName_array = isset($_POST['taskName']) ? $_POST['taskName'] : array();
$colors_array = isset($_POST['colors']) ? $_POST['colors'] : array();
$colors_array = explode(',', $colors_array);
// This outputs:
// Array
// (
// [0] => Gray
// [1] => Blue
// [2] => Orange
// [3] => Red
// [4] => Yellow
// )
$total_rows = count($taskName_array);
for ($i = 0; $i < $total_rows; $i++) {
echo $taskName_array[$i];
// Begin loop through status (Expecting not all statuses just the ones in the same div)
for ($a = 0; $a < $colors_array ; $a++) {
// I'm aware this would echo all the colors (not what I want) vs just the corresponding colors.
echo $colors_array[$a];
}
}
预期结果类似于“Task1-gray, blue, orange | Task2-red, yellow” 如果不清楚或需要更多信息,请告诉我。
【问题讨论】:
标签: javascript php html arrays