如何用JavaScript获取PHP生成的按钮值并通过AJAX传递给PHP页面
问题原因
你原有的代码存在两个核心问题:
document.querySelectorAll('.link-show')返回的是所有匹配类名的按钮节点集合,直接取.value无法获取到单个按钮的实际值- 你在绑定点击事件前就固定读取了id变量,没有在点击触发时动态获取当前被点击按钮的value,导致所有按钮发送的参数都是错误值
代码修改方案
1. 修复后的JavaScript代码
<script> document.querySelectorAll('.link-show').forEach(item => { item.addEventListener('click', event => { // 点击触发时动态获取当前被点击按钮的value const id = event.target.value; var xhr = new XMLHttpRequest(); // 对参数做编码处理避免特殊字符问题 xhr.open('GET','validations/retrievebycategory.php?id='+encodeURIComponent(id), true); xhr.onload = function(){ if(this.status === 200){ console.log(this.responseText); // 此处可添加你后续处理返回productId列表的逻辑 } } xhr.send(); }) }) </script>
2. 后端PHP安全优化建议
你现有代码存在SQL注入风险,建议retrievebycategory.php使用预处理语句处理查询逻辑,参考写法如下:
<?php include "validations/connection.php"; $productIds = []; // 校验传入参数合法性 if(isset($_GET['id']) && is_numeric($_GET['id'])){ $categoryId = $_GET['id']; // 预处理语句避免SQL注入 $stmt = $conn->prepare("SELECT productId FROM products WHERE categoryId = ?"); $stmt->bind_param("i", $categoryId); $stmt->execute(); $result = $stmt->get_result(); while($row = $result->fetch_assoc()){ $productIds[] = $row['productId']; } // 可以返回JSON格式给前端处理 echo json_encode($productIds); $stmt->close(); } $conn->close(); ?>
内容的提问来源于stack exchange,提问作者Igor Kabirigi
相关产品推荐
相关产品推荐

