我在下面有 php/mysqli 和 jquery 代码,它显示了一个课程下拉菜单和一个模块下拉菜单:
$courseactive = 1;
$sql = "SELECT CourseId, CourseNo, CourseName FROM Course WHERE CourseActive = ? ORDER BY CourseNo";
$sqlstmt=$mysqli->prepare($sql);
$sqlstmt->bind_param("i",$courseactive);
$sqlstmt->execute();
$sqlstmt->bind_result($dbCourseId, $dbCourseNo, $dbCourseName);
$courses = array(); // easier if you don't use generic names for data
$courseHTML = "";
$courseHTML .= '<select name="courses" id="coursesDrop" onchange="getModules();">'.PHP_EOL;
$courseHTML .= '<option value="">Please Select</option>'.PHP_EOL;
$outputcourse = "";
while($sqlstmt->fetch())
{
$course = $dbCourseId;
$courseno = $dbCourseNo;
$coursename = $dbCourseName;
$courseHTML .= "<option value='".$course."'>" . $courseno . " - " . $coursename . "</option>".PHP_EOL;
if (isset($_POST['courses']) && ($_POST['courses'] == $course)) {
$outputcourse = "<p><strong>Course:</strong> " . $courseno . " - " . $coursename . "</p>";
}
}
$courseHTML .= '</select>';
$moduleHTML = "";
$moduleHTML .= '<select name="modules" id="modulesDrop">'.PHP_EOL;
$moduleHTML .= '<option value="">Please Select</option>'.PHP_EOL;
$moduleHTML .= '</select>';
$pHTML = "";
?>
<script type="text/javascript">
function getModules() {
var course = jQuery("#coursesDrop").val();
jQuery('#modulesDrop').empty();
jQuery('#modulesDrop').html('<option value="">Please Select</option>');
jQuery.ajax({
type: "post",
url: "module.php",
data: { course:course },
success: function(response){
jQuery('#modulesDrop').append(response);
}
});
}
</script>
上面代码中发生的情况是,当用户从课程下拉菜单中选择课程时,它将导航到 module.php 页面,在该脚本中它将执行查询并输出属于该课程的模块此页面上的模块下拉菜单。
但现在我想根本不包括课程下拉菜单,因为它并不是真正需要的。所以我只有一个模块下拉菜单。我仍然希望通过仍然导航到 module.php 脚本来显示模块以显示模块选项。
所以我的问题是,我需要在 jquery 代码中进行哪些更改,以便当我打开上述脚本时,它将立即执行 jquery 并在下拉菜单中显示模块列表(不依赖于 Course drop下拉菜单,因为该下拉菜单将被删除)?
我假设 jquery 需要进入 document.ready() 函数?
更新:
<script type="text/javascript">
$(document).ready( function(){
function getModules() {
jQuery.ajax({
type: "post",
url: "module.php",
success: function(response){
jQuery('#modulesDrop').append(response);
}
});
});
}
</script>
module.php 页面:
`
// connect to the database
include('connect.php');
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}
$moduleactive = 1;
$sql = "SELECT ModuleId, ModuleNo, ModuleName FROM Module WHERE ModuleActive = ? ORDER BY ModuleNo";
$sqlstmt=$mysqli->prepare($sql);
$sqlstmt->bind_param("i", $moduleactive);
$sqlstmt->execute();
$sqlstmt->bind_result($dbModuleId,$dbModuleNo,$dbModuleName);
$moduleHTML = "";
while($sqlstmt->fetch()) {
$moduleHTML .= sprintf('<option value="%1$s_%2$s_%3$s">%1$s - %2$s</option>'.PHP_EOL, $dbModuleNo, $dbModuleName, $dbModuleId);
}
echo $moduleHTML;
$sqlstmt->execute();
?>`