我正在开发一个非常简单的课程目录。我正在使用动态选择下拉菜单来显示特定courses
提供的academy
。最初,我在这些选择菜单中显示courses available
的完整列表,其中包含名为courses_selection_list
的mysql数据库表中的值。然后,我通过标记值academy_id=15
来选择selected=selected
提供的课程。在Jquery / JS中,您将看到我正在对文件getCourses.php
进行一次ajax调用,然后在页面加载时显示选择菜单。
我的问题如下:我只能显示academy_id=15
提供的课程的一个值。我该如何显示它们?或者有更好的方法吗? DEMO
<script>
var option = $('#courses_offered').val();
showFields(option);
function showFields(option){
var content = '';
for (var i = 1; i <= option; i++){
var content = '';
for (var i = 1; i <= option; i++){
(function(i) {
$.ajax({
type: "POST",
url: "getCourses.php",
data: {
value: option
},
success: function (data) {
content += '<div id="course_'+i+'">'
+'<label>Course # '+i+'</label><br />'
+'<label>Course Name:</label>'
+'<select id="coursename_'+i+'" name="coursename_'+i+'" class="course_list">'
+'<option value="" >--- Select ---</option>"';
content += data;
content += '</select></div></br>';
$('#course_catalog').html(content);
}
});
})(i);
}
$('#course_catalog').html(content);
}
$('#course_catalog').html(content);
}
</script>
<select name="courses_offered" id="courses_offered" disabled>
<?php
$db_select2 = $db_con->prepare("
SELECT academy_id
FROM courses_by_academy
WHERE academy_id = :id
");
if (!$db_select2) return false;
if (!$db_select2->execute(array(':id' => $id))) return false;
$courses_count = $db_select2->rowCount();
echo "<option>----Select----</option>";
echo "<option value=\"1\"". (($courses_count=="1")?"selected=\"selected\"":"") .">1</option>";
echo "<option value=\"2\"". (($courses_count=="2")?"selected=\"selected\"":"") .">2</option>";
echo "<option value=\"3\"". (($courses_count=="3")?"selected=\"selected\"":"") .">3</option>";
echo "<option value=\"4\"". (($courses_count=="4")?"selected=\"selected\"":"") .">4</option>";
echo "<option value=\"5\"". (($courses_count=="5")?"selected=\"selected\"":"") .">5</option>";
?>
</select>
<div id="course_catalog"></div>
getCourses.php
- 课程价值
$id = 15;
//get the course list
$course_query = $db_con->prepare("SELECT course_id, course_name FROM courses_selection_list;");
$course_query->execute();
$data = $course_query->fetchAll();
foreach ($data as $row){
//select the courses being offered by academy_id=15
$option = "<option value='".$row["course_id"].":".$row["course_name"]."'";
$db_select = $db_con->prepare("
SELECT academy_id, course_name, course_id,
course_start_date, course_end_date
FROM courses_by_academy
WHERE academy_id = :id
");
if (!$db_select) return false;
if (!$db_select->execute(array(':id' => $id))) return false;
$results = $db_select->fetchAll(\PDO::FETCH_ASSOC);
if (empty($results)) return false;
foreach ($results as $value) {
$result= $value['course_id'];
if ($result == $row['course_id']) {
$option .= "selected='selected'";
}
}
$option .= ">". $row['course_name'] ."</option>";
//show result
echo $option;
}
Mysql Tables示例:
courses_selection_list
+-----------+-------------------------+
| course_id | course_name |
+-----------+-------------------------+
| 1 | Math |
| 2 | English |
| 3 | Science |
| 4 | Other- Not Listed |
| 5 | Social Studies |
| 6 | Home Mac |
| 7 | Business Management |
| 8 | Psychology |
| 9 | Accounting |
| 10 | Advanced Networks |
| 11 | Information Techonology |
+-----------+-------------------------+
courses_by_academy
+----+------------+--------------------------+-----------+------------+----------+
| id | academy_id | course_name | course_id | start_date |end_date |
+----+------------+--------------------------+-----------+------------+----------+
| 1 | 15 | Science | 3 |2013-12-04 |2013-12-25|
| 2 | 15 | Business Management | 7 |2013-12-04 |2013-12-25|
| 3 | 15 | Information Technology | 11 |2013-12-04 |2013-12-25|
+----+------------+--------------------------+-----------+------------+----------+
期望的结果:
答案 0 :(得分:4)
Javascript插入document.ready事件
var option = 3,
$course_catalog = $('#course_catalog');
showFields(option);
function showFields(option){
$course_catalog.html('');
// request only once
$.ajax({
type: "POST",
url: "getCourses.php",
async : false,
data: {
value : option
},
dataType : 'json',
contentType : 'application/json',
success: function (data) {
for (var i = 1; i <= option; i++){
// prepare select
$course_catalog.append('<div id="course_' + i + '"><label>Course # '+i+'</label><br />'
+'<label>Course Name:</label>'
+'<select id="coursename_'+i+'" name="coursename_'+i+'" class="course_list">'
+'<option value="" >--- Select ---</option>"'
+'</select><br/><p id="date_'+i+'"></p></div></br>');
var $el = $course_catalog.find('#coursename_' + i),
val = 0,
index = 1;
for(var n in data) {
var o = data[n];
if (o.academy_id > 0) {
if (index == i) {
val = o.id + ':' + o.name;
$course_catalog.find('#date_'+i).html('Start at: ' + o.start_date + ' until '+o.end_date);
}
index ++;
}
$el.append('<option value="' + o.id + ':' + o.name + '">'+o.name+'</option>');
}
$el.val(val);
}
}
});
}
PHP代码:
header("Content-type: application/json");
$id = 15;
//get the course list
$course_query = $db_con->prepare("
SELECT
t.course_id, t.course_name, IFNULL(lj.academy_id, 0) as academy_id, lj.course_start_date, lj.course_end_date
FROM courses_selection_list as t
LEFT JOIN courses_by_academy as lj
ON (lj.course_id = t.course_id AND lj.academy_id = :id)
ORDER BY t.course_id
");
$course_query->execute(array(':id' => $id));
$data = $course_query->fetchAll();
$course_data = array();
foreach ($data as $row) {
$course_data[] = array(
"id" => $row["course_id"],
"name" => $row["course_name"],
"academy_id" => $row["academy_id"],
"start_date" => $row["course_start_date"],
"end_date" => $row["course_end_date"],
);
} // foreach ($data as $row) {
echo json_encode($course_data);
答案 1 :(得分:1)
假设您有一个列出所有可用院校的选择框:
<select name="academy" id="acadaemy">
<option value="1">Academy1</option>
.............................
.............................
<option value="15">Academy15</option>
</select>
然后,您可以为此选项绑定onchange事件以显示所需的课程。
$('#acadaemy').on('change', function() {
var option = this.value;
$.ajax({
type: "POST",
url: "getCourses.php",
data: {
'ac_id': option
},
success: function (data) {
$('#course_catalog').html(data);
}
});
});
在你的getCourses.php中
Step 1: fetch the POST value (here $_POST['ac_id']) and validate it
Step 2: Get all courses.
Step 3: Get all courses with specified academy id
Step 4: Iterate result from step 3 and create each select tag.
Step 5: Iterate result from Step 2 and create option tags and set selected.
Step 6: Echo back the result.
<?php
$id = $_POST['ac_id'];
//Do something here to validate the post data
$course_query = $db_con->prepare("SELECT course_id, course_name FROM courses_selection_list;");
$course_query->execute();
$data = $course_query->fetchAll();//All courses here
$db_select = $db_con->prepare("
SELECT academy_id, course_name, course_id,
course_start_date, course_end_date
FROM courses_by_academy
WHERE academy_id = :id
");
$resultStr = '';
if (!$db_select) return false;
if (!$db_select->execute(array(':id' => $id))) return false;
$results = $db_select->fetchAll(\PDO::FETCH_ASSOC); // academy specific courses here
if (empty($results)) return false;
foreach ($results as $value) { // iterate academy courses
$resultStr .= '<div class="course">';
$resultStr .= '<select name="coursename[]" class="course_list">';
foreach ($data as $row){ // iterate all courses
$result .= "<option value='".$row["course_id"].":".$row["course_name"]."'";
if ($result['course_id'] == $row['course_id']) {
$resultStr .= " selected='selected'";
}
$resultStr .= ">". $row['course_name'] ."</option>";
}
$resultStr .= '</select>';
$resultStr .= '</div>';
}
echo $resultStr;
exit();
?>
答案 2 :(得分:0)
这不起作用的原因是您的SQL查询顺序错误。您首先要获取courses_by_academy
,然后从courses_selection_list
获取相应的课程。
此外,您在此上下文中使用Javascript的方法有点不合理,因此我删除了它以显示下拉列表。
<?php
$id = 15;
//get the course list
$db_select = $db_con->prepare("
SELECT academy_id, course_name, course_id,
course_start_date, course_end_date
FROM courses_by_academy
WHERE academy_id = :id
");
if (!$db_select) return false;
if (!$db_select->execute(array(':id' => $id))) return false;
$results = $db_select->fetchAll(\PDO::FETCH_ASSOC);
if (empty($results)) return false;
foreach ($results as $value) {
$course_query = $db_con->prepare("SELECT course_id, course_name FROM courses_selection_list;");
$course_query->execute();
$data = $course_query->fetchAll();
$i = 0;
foreach ($data as $row){
$i += 1;
echo '<div class="courses">';
echo '<label>Course # <span>', $i, '</span></label><br />';
echo '<label>Course Name:</label>';
echo '<select name="coursename[]" class="course_list">';
echo '<option>--- Select ---</option>"';
echo "<option value='".$row["course_id"].":".$row["course_name"]."'";
if ($value['course_id'] == $row['course_id']) {
echo " selected='selected'";
}
echo ">". $row['course_name'] ."</option>";
}
echo '</select></div></br>';
请注意我是如何使用coursename[]
作为SELECT的名称:使用此函数,PHP将在POST请求中将其作为数组接收为$_POST["coursename"]
,以便您可以使用foreach
通过他们。
我认为Javascript意味着能够改变课程数量?我会采取不同的方法:
$("#courses_offered").on("change", function() {
var number_of_courses_offered = $('#courses_offered').val();
var course_divs = $("div.courses");
if (number_of_courses_offered < 1) {
course_divs.hide();
return;
}
course_divs.show();
// to few courses displayed: add another one until the number fits
while (course_divs.length < number_of_courses_offered) {
// create an empty course div by using the first one and removing the
// selected attribute so that the first item "--- Select" is displayed
var single_course_div = course_divs.first().clone(true);
single_course_div.find("option:selected").removeAttr("selected");
// fix the course number
single_course_div.find("span").text(course_divs.length + 1);
// insert it after the last of the divs
course_divs.last().after(single_course_div);
course_divs = $("div.courses"); // update for the next while loop
}
// too many courses displayed: remove the last ones
while (course_divs.length > number_of_courses_offered) {
// remove the last div
course_divs.last().remove();
course_divs = $("div.courses"); // update for the next while loop
}
});