JS循环获取多组同名输入框值并提交PHP入库的问题
问题原因
document.getElementsByName("com")返回的是包含所有同名输入框的DOM集合,直接取.value只会读取第一个元素的属性,因此只能拿到第一条评论- 提交数据时仅传递了单个值,后端也只处理单条数据,无法批量存储多条商品评论
- 现有输入框没有绑定对应商品ID,就算收集到所有评论也无法对应到具体的购物车商品
修改步骤
1. 调整输入框结构
循环生成输入框时,去掉重复的id(HTML中id必须唯一),新增class用于选择,同时通过data-*属性绑定对应商品ID:
<td style="vertical-align: middle; white-space: nowrap; text-align: right;"> <input type="text" class="item-comment" data-item-id="<?php echo $当前循环的商品ID; ?>" placeholder="Enter comment"> </td>
2. 调整前端数据收集与提交逻辑
遍历所有输入框收集评论,组装成数组后提交:
// 收集所有非空评论 const commentList = [] document.querySelectorAll('.item-comment').forEach(input => { const content = input.value.trim() if (content) { commentList.push({ item_id: input.dataset.itemId, content: content }) } }) // AJAX提交调整 jQuery.ajax({ type: "POST", async: true, url: "/content/shop/order_process/ajax_checkout_create.php", dataType: "json", // 直接传递对象,jQuery会自动处理编码 data: { item_comments: commentList }, success: function(answer) { if(answer.status == true) { <?php if($user_id != 0) { ?> location = "/shop/orders/order?order_id="+answer.order_id+"&success_message="+encodeURI("Order created"); <?php } else { ?> location = "/shop/orders/orders-without-reg"; <?php } ?> } else { alert(answer.message); document.getElementById("confirm_loader").style.display = 'none'; document.getElementById("confirm_btn").style.display = 'inline'; return false; } } });
3. 调整后端接收与存库逻辑
遍历接收的评论数组,逐行插入数据库:
if (!empty($_POST["item_comments"]) && is_array($_POST["item_comments"])) { foreach ($_POST["item_comments"] as $comment) { $order_item_id = intval($comment['item_id']); $item_comment = trim($comment['content']); $item_comment = htmlentities($item_comment); $item_comment = str_replace(["\r", "\t"], "", $item_comment); $item_comment = str_replace("\n", "<br/>", $item_comment); $stmt = $db_link->prepare('INSERT INTO `shop_orders_items_comment` (`order_id`, `order_item_id`, `text`) VALUES (?,?,?);'); $stmt->execute([$order_id, $order_item_id, $item_comment]); } }
补充说明
建议新增校验逻辑:存库前验证order_item_id对应的商品确实属于当前用户的本次订单,避免恶意提交篡改其他订单的评论。
内容的提问来源于stack exchange,提问作者Edijs Maļinovskis
相关产品推荐
相关产品推荐

