使用PHP与JQuery将MySQL数据填充到动态输入时位置错误问题
问题排查与修复方案
1. 核心问题:Ajax回调中this指向错误
$.ajax的success回调函数默认上下文是Ajax请求的配置对象,不是触发change事件的下拉选择器元素,因此$(this).parents('.getval')无法定位到当前操作对应的容器,最终导致填充错位。
2. 适配问题:静态HTML缺失定位类
动态生成的表单块的内容容器加了getval类,但初始静态写死的HTML中<div class="body">没有添加该类,会导致第一个下拉选择器触发后无法找到对应价格输入框。
3. 安全隐患:PHP存在SQL注入风险
你虽然使用了PDO的prepare方法,但直接把用户传入的参数拼接进SQL语句,完全没有用到预处理的参数绑定能力,存在严重的SQL注入漏洞。
具体修复代码
修正jQuery逻辑
提前存储触发事件的元素上下文,避免this指向错误:
$(document).on('change', '[name^=itemname]', function() { // 提前存储当前触发事件的下拉选择器 const $currentSelect = $(this); var code = $currentSelect.val(); $.ajax({ type: 'POST', url: 'pages/GetPrice.php', data:{code:code}, success: function(data){ // 直接用公共的body类定位父容器,不需要额外加getval类 $currentSelect.parents('.body').find('[name^=price]').val(data); }, error: function (jqXHR, textStatus, errorThrown){ alert(errorThrown); } }); });
修复PHP SQL注入问题
改用预处理参数绑定写法:
<?php require 'DBConnection.php'; $code=''; if(isset($_POST["code"])){ $id = $_POST["code"]; // 用占位符替代直接拼接变量 $get_c = $pdo->prepare("SELECT * FROM all_menu WHERE `item_name` = ?"); // 绑定参数后执行 $get_c->execute([$id]); while ($row = $get_c->fetch()) { $code .= $row['price']; } echo $code; } ?>
内容的提问来源于stack exchange,提问作者Hazem El-behairy
相关产品推荐
相关产品推荐

