如何在Moodle中实现基于SQL查询的联动下拉列表?
问题排查与修复方案
1. 修正jQuery加载顺序与重复加载问题
Moodle已通过$PAGE->requires->jquery()加载jQuery,你在validation.php中重复加载会导致冲突,且依赖jQuery的插件需在jQuery之后加载。修改validation.php的脚本顺序并移除重复的jQuery加载:
<!-- 先加载jQuery(Moodle已加载时可省略,若需兼容可保留) --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <!-- 依赖jQuery的插件需后置加载 --> <script src="https://www.jqueryscript.net/demo/Dialog-Modal-Dialogify/dist/dialogify.min.js"></script> <script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.13.1/datatables.min.js"></script> <script> function branchelist(){ const branche_id = $("#id_branche").val(); // 使用绝对路径避免相对路径错误,需替换为你的Moodle站点根路径 const getterUrl = "/local/regform/classes/forms/getter.php"; $("#id_year").load(getterUrl + "?brancheid=" + branche_id); } </script>
2. 修复getter.php的SQL安全与路径问题
- 先通过浏览器直接访问
你的Moodle域名/local/regform/classes/forms/getter.php?brancheid=1,确认文件可访问且返回正确的<option>标签。 - 将SQL改为参数化查询避免注入风险,同时修复HTML输出的语法问题:
<?php require_once (__DIR__ .'/../../config.php'); global $DB; $brancheid = optional_param('brancheid', 0, PARAM_INT); if($brancheid > 0) { // 参数化查询,安全获取数据 $year_array = $DB->get_records('course_categories', ['parent' => $brancheid], '', 'id, name'); echo "<option value='0'>All Students</option>"; foreach ($year_array as $year) { // 给value加引号,转义内容避免HTML错误 echo "<option value='{$year->id}'>" . htmlspecialchars($year->name) . "</option>"; } } else { // 分支ID无效时返回默认选项 echo "<option value='0'>select year</option>"; }
3. 替换load方法为更可靠的$.get请求
load()可能因缓存或DOM解析问题失效,改用$.get()手动更新下拉框:
function branchelist(){ const branche_id = $("#id_branche").val(); const getterUrl = "/local/regform/classes/forms/getter.php"; $.get(getterUrl, { brancheid: branche_id }, function(data) { $("#id_year").empty().html(data); }).fail(function() { alert("加载年份数据失败,请检查路径或后台服务"); }); }
4. 验证DOM元素ID
通过浏览器开发者工具检查页面HTML,确认年份下拉框的ID确实是id_year(Moodle表单元素ID默认是id_+元素名,此处应为正确值)。
5. 检查Moodle权限
确保getter.php允许当前用户访问,若表单面向未登录用户,需在getter.php中添加必要的权限校验,避免因权限拦截返回空内容。
内容的提问来源于stack exchange,提问作者Mohamed Mahmoud
相关产品推荐
相关产品推荐

