PHP+jQuery二级联动select选择框不加载 AJAX请求未触发排查
问题根因与修复方案
核心问题(AJAX完全不触发的直接原因)
- 动态元素事件绑定失效:你的
product_id下拉框是通过add_product_row函数动态插入到页面的,页面初始加载执行$('#product_id').change()绑事件的时候,这个DOM元素还不存在,事件根本没有绑定成功,自然不会触发AJAX请求。 - 重复ID冲突:所有动态生成的产品下拉框都用了同一个
id="product_id",HTML里ID必须全局唯一,重复ID会导致jQuery选择器只能匹配到第一个元素,后续新增行的下拉框完全无法被选中。 - 联动目标定位错误:你AJAX成功后固定填充
$('#month_id'),但月份下拉框的ID都是带count后缀的(month_id+count),根本不存在id="month_id"的元素,就算AJAX触发了也没法正确填充。
次要代码bug(后续会触发的问题)
function.php中fill_month_list_product_wise函数参数拼写错误:定义的参数是$poduct_id(少了字母r),但查询里用的是$product_id,会导致变量未定义报错。- 同函数SQL语句排序字段错误:写的是
ORDER BY monat_id,应该对应表字段为month_id。 fill_product_list函数中$query赋值开头丢了双引号,存在PHP语法错误。
修复步骤
1. 修改动态生成下拉框的ID,新增通用class
修改add_product_row里的产品下拉框代码:
// 把原来的id="product_id"改成带count后缀,新增product-select通用class html += '<select name="product_id[]" id="product_id'+count+'" class="form-control selectpicker product-select" data-live-search="true" required>';
2. 改用事件委托绑定change事件
把原来的$('#product_id').change(...)替换成以下代码:
// 把事件绑定在页面初始就存在的父元素#span_product_details上,匹配.product-select的change事件 $(document).on('change', '.product-select', function(){ // 获取当前触发事件的产品下拉框所在行的count值 var row_id = $(this).closest('span').attr('id').replace('row',''); var product_id = $(this).val(); var btn_action = 'load_month'; $.ajax({ url:"action.php", method:"POST", data:{product_id:product_id, btn_action:btn_action}, success:function(data) { // 填充对应行的月份下拉框 $('#month_id'+row_id).html(data); // 刷新selectpicker组件样式,避免新增选项不显示 $('#month_id'+row_id).selectpicker('refresh'); } }); });
3. 修复function.php的语法错误
修正fill_product_list的$query引号:
function fill_product_list($connect) { $query = " SELECT * FROM product WHERE product_status = 'active' ORDER BY product_name ASC "; // 后续代码不变 }
修正fill_month_list_product_wise的参数和排序字段:
// 参数拼写修正 function fill_month_list_product_wise($connect, $product_id) { $query = " SELECT * FROM month INNER JOIN stock ON stock.month_id = month.month_id WHERE stock.product_id = '".$product_id."' // 排序字段修正 ORDER BY month_id ASC "; // 后续代码不变 }
内容的提问来源于stack exchange,提问作者Max
相关产品推荐
相关产品推荐

