我現在要寫下這個過程如何完成,然後你將不得不爲你不明白的部分找到教程。
所以: 1步:從數據庫中獲取的水平,併產生水平的下拉列表:
<select id="level">
<option value="p1">p2</option>
<option value="p2">p2</option>
</select>
2步:準備選擇框主題:
<select id="subjects" style="display:none"> //this field should be hidden first
</select>
3步:使用jQuery,爲「級別」選擇框添加監聽器(這意味着每次用戶選擇任何級別(p1,p2 ...)時都會執行此功能:
<script>
$('#level').on('change', function() { //this chunk of code will be executed every time user reselects level value
var selected = $(this).val(); //this is the value of selected level
//here starts ajax method to communicate with server
$.ajax({
method: "POST",
url: "getSubjectByLevel.php",
data: { level: selected } //level is variable that will passed to getSubjectByLevel.php. You can get it in php file using $_POST["level"] and according this value generate sql query that will return only subject with this "level". Then you will have to generate array out of these subjects and return using normal "echo ArrayName" statement.
})
.done(function(subjects) { //subjects is array of subjects returned from getSubjectByLevel.php
var selectBoxHtml = '';
for(i =0; i< subjects.length; i++){
selectBoxHtml += '<option value='+subjects[i]+'>'+subjects[i]+'</option>';
}
$("#subjects").html(selectBoxHtml); //put generated select box options in prepared earlier subjects select box
$("#subjects").show(); //appear subjects select box which was hidden initially
});
});
</script>
這是一種實現你想要的一般算法。如果您有關於細節或概念問題的問題,您無法理解,請隨時詢問。
嘗試學習Ajax。 http://www.w3schools.com/ajax/ajax_examples.asp –
您可能想要將Ajax與後端腳本結合使用來執行此操作。 ajax函數將作爲偵聽器附加到第一個下拉菜單上 - 當用戶從菜單中選擇一個項目時,ajax函數將請求發送到構建和執行sql語句的後端腳本。查詢結果被髮送回javascript函數,該函數使用回調函數處理數據(回調會生成第二個菜單的內容)〜至少,這是一種方法! – RamRaider
任何參考例子? :) – John