英文:
Push the value to input array field
问题
以下是翻译好的部分:
如何向具有名称为数组的输入添加元素?
<input type="hidden" class="deleted-images" name="deletedImages[]" value="">
在 PHP 输出中,我希望得到一个数组:
deletedImages => [1,2,...n]
英文:
How can I add elements to input with name as array?
<input type="hidden" class="deleted-images" name="deletedImages[]" value="">
const deleteButtons = document.querySelectorAll('.delete-resource');
const removedImagesInput = document.querySelector('.deleted-images');
deleteButtons.forEach((item) => {
item.addEventListener('click', function () {
item.closest('.input-photo-preview').style.display = 'none';
removedImagesInput.value += parseInt(item.getAttribute('data-image-id')) + ',';
});
})
At the output in PHP I want to get an array:
deletedImages => [1,2,...n]
答案1
得分: 2
为了让PHP接收一个数组,您需要具有多个元素,它们的name
属性应为"deletedImages[]"
。
例如,您可以为每个新值克隆您现有的.deletedImages
元素:
const deleteButtons = document.querySelectorAll('.delete-resource');
const removedImagesInput = document.querySelector('.deleted-images');
const removedImagesInputParent = removedImagesInput.parentNode;
// 防止提交空值
removedImagesInputParent.removeChild(removedImagesInput);
deleteButtons.forEach((item) => {
item.addEventListener('click', function () {
item.closest('.input-photo-preview').style.display = 'none';
// 创建新的<input>元素
const elInput = removedImagesInput.cloneNode(false);
elInput.value = item.getAttribute('data-image-id');
// 将新的<input>插入DOM中
removedImagesInputParent.appendChild(elInput);
});
})
否则,您需要发送JSON或逗号分隔的文本(就像您的尝试一样),然后在PHP中解码它成为一个数组,类似于:
$deletedImages = explode(",", $_POST['deletedImages']);
英文:
In order for PHP to receive an array, you'd need multiple elements with name="deletedImages[]"
.
For example, you can clone your existing .deletedImages
element for each new value:
const deleteButtons = document.querySelectorAll('.delete-resource');
const removedImagesInput = document.querySelector('.deleted-images');
const removedImagesInputParent = removedImagesInput.parentNode;
//prevent submitting empty value
removedImagesInputParent.removeChild(removedImagesInput);
deleteButtons.forEach((item) => {
item.addEventListener('click', function () {
item.closest('.input-photo-preview').style.display = 'none';
//create new <input> element
const elInput = removedImagesInput.cloneNode(false);
elInput.value = item.getAttribute('data-image-id');
//insert new <input> into DOM
removedImagesInputParent.appendChild(elInput);
});
})
Otherwise, you'd need send JSON or comma separated text (as your attempt does) and in php decode it into an array with something like:
$deletedImages = explode(",", $_POST['deletedImages']);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论