問題描述
很簡單,我有一個動態(tài)填充數(shù)據(jù)的下拉菜單:
Very simply, I have one dropdown menu dynamically populated with data:
SQL 代碼
$querycourse = "SELECT course, COUNT(course) AS count FROM acme WHERE course IS NOT NULL GROUP BY course ";
$procc = mysqli_prepare($link, $querycourse);
$queryc = mysqli_query($link, $querycourse) or die(mysqli_error($link));
PHP 代碼
echo "<select name='course[]' value='' multiple='multiple' size=10>";
// printing the list box select command
echo "<option value=''>All</option>";
while($ntc=mysqli_fetch_array($queryc)){//Array or records stored in $nt
echo "<option value="$ntc[course]">"$ntc[course]"</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
我需要的是另一個下拉列表,其中填充了基于第一個下拉框中選擇的數(shù)據(jù).
What I need is another dropdown that is populated with data based on a selection from the first dropdown box.
我正在使用 MySQL、PHP、Javascript,也可以(一推)使用 jQuery.我沒有使用 Ajax 的經(jīng)驗.
I am using MySQL, PHP, Javascript and can also (at a push) use jQuery. I have no experience in Ajax.
有人愿意為我指出正確的方向嗎?!
Would anyone be kind enough to point me in the right direction?!
提前致謝,一如既往,
荷馬.
推薦答案
第一種和最好的方法(如果您有或可能有足夠的選項特定數(shù)據(jù))
使用 AJAX.我認為,與其他實現(xiàn)相同的方法相比,這是最簡單的方法.使用Jquery 實現(xiàn)AJAX.它讓 AJAX 變得輕而易舉!在這里,我為你分享我的一塊蛋糕 -
First and Best Method (If you have or may have enough option specific data)
Use AJAX. It is the easiest way, I think, compared to the other ways to implement the same. Use Jquery to implement AJAX. It makes AJAX a piece of cake! Here I share my piece of cake for you -
以下是您需要的大致完整代碼 -
Following is roughly the complete code you need -
像這樣在您的第一個選擇中調(diào)用一個 javascript 函數(shù) populateSecondDropdown() -
Call a javascript function populateSecondDropdown() on your first select like this -
echo "<select name='course[]' value='' multiple='multiple' size=10 onchange='populateSecondDropdown(this, 'http://yourprojectUrl','Any Subject');'>";
// printing the list box select command
echo "<option value=''>All</option>";
while($ntc=mysqli_fetch_array($queryc))
{//Array or records stored in $nt
echo "<option value="$ntc[course]">"$ntc[course]"</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
在populateSecondDropdown()函數(shù)內(nèi)部定義一個ajax調(diào)用 -
Define an ajax call inside inside the populateSecondDropdown() function -
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
function populateSecondDropdown(object,baseUrl)
{
$.ajax({
type: "POST",
url: baseUrl+"/ajax/fetchOptions.php",
data: { id_option: $(object).val(), operation: 'get_subjects' },
dataType: "json",
success: function(data)
{
//Clear options corresponding to earlier option of first dropdown
$('select#secondDropdown').empty();
$('select#secondDropdown').append('<option value="0">Select Option</option>');
//Populate options of the second dropdown
$.each( data.subjects, function()
{
$('select#secondDropdown').append('<option value="'+$(this).attr('option_id')+'">'+$(this).attr('option_name')+'</option>');
});
$('select#secondDropdown').focus();
},
beforeSend: function()
{
$('select#secondDropdown').empty();
$('select#secondDropdown').append('<option value="0">Loading...</option>');
},
error: function()
{
$('select#secondDropdown').attr('disabled', true);
$('select#secondDropdown').empty();
$('select#secondDropdown').append('<option value="0">No Options</option>');
}
});
}
</script>
最后是在 AJAX 處理器文件 fetchOptions.php 中獲取第二個下拉選項的查詢.您可以在此處使用 $_POST['id_option'] 來獲取其下的選項.此處的數(shù)據(jù)庫查詢應獲取每個選項的
option_id
和option_name
字段(正如$.each
中的 jquery 代碼所預期的那樣)并返回一個json 編碼的數(shù)組是這樣的:-And finally the query to fetch 2nd dropdown's options in the AJAX processor file fetchOptions.php. You can use $_POST['id_option'] here to fetch the options under it. The database query here should fetch the
option_id
andoption_name
fields for every option (as expected by the jquery code inside$.each
) and return a json encoded array like this:-return json_encode(array("subjects" => $resultOfQuery));
獲取按第一個下拉列表的字段分組的第二個下拉列表的所有數(shù)據(jù).例如.讓我們學習第一個下拉菜單中顯示的課程和第二個顯示的課程下的科目
Fetch all the data for the second dropdown grouped by the field of the first dropdown. E.g. let's take courses displayed in the first dropdown and subjects under courses displayed in the 2nd
創(chuàng)建第二個下拉列表的所有選項.在創(chuàng)建如下選項時分配與課程相同的課程:-
Create all the options of the 2nd dropdown. Assign classes equal to the courses while creating the options like this:-
第二種方法(僅使用 javascript)
$querycourse = "SELECT course, subject FROM subjects WHERE subject IS NOT NULL GROUP BY course "; $procc = mysqli_prepare($link, $querycourse); $queryc = mysqli_query($link, $querycourse) or die(mysqli_error($link)); echo "<select name='subjects[]' value='' multiple='multiple' size=100>"; echo "<option value=''>All</option>"; while($ntc=mysqli_fetch_array($queryc)) {//Array or records stored in $nt echo "<option value="$ntc[subject]" class="$ntc[course]">"$ntc[subject]"</option>"; } echo "</select>";
然后為第一個下拉列表定義
onchange="displaySubjectsUnderThisCourse(this);"
并編寫此 javascript :-Then define
onchange="displaySubjectsUnderThisCourse(this);"
for the first dropdown and write this javascript :-function displaySubjectsUnderThisCourse(object) { var selectedCourse = $(object).val(); //Display the options with class = the selected option from first dropdown $("."+selectedCourse).removeClass("hidden"); //define a class hidden with display:none; $('option:not(.selectedCourse)').hide(); // hide all options whose class is other than selectedCourse - Not sure whether this will work or not, though //Deselect any previous selections //If single option selection is allowed $('select#secondDropdown option').attr('selected', false); // or following if multiple selection is allowed (needed for IE) $('select#secondDropdown option').attr('selectedIndex', -1); }
這里的基本思想是隱藏/顯示選項組,但我的代碼可能有錯誤.
The basic idea here is to hide/display option groups but my code may have errors.
最后,請注意,第二種方法(獲取所有選項值)只有在您的數(shù)據(jù)量有限并且非常確定將來數(shù)據(jù)量總是會減少的情況下才會更好.但是,由于沒有人能夠?qū)ξ磥砣绱舜_定,因此建議始終使用 AJAX 方法.
Finally, please note, the second method (fetching all the option values) would be better only if you have limited small amount of data and are very sure there will always be less data in future. But, since nobody can be so certain about the future, it is advisable to use the AJAX method always.
這篇關于根據(jù)另一個下拉列表填充下拉列表的最佳和最簡單的方法是什么的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權益,請聯(lián)系我們刪除處理,感謝您的支持!