简体   繁体   English

根据另一个下拉列表填充下拉列表的最佳和最简单的方法是什么

[英]What's the best and easiest way to Populate a dropdown based on another dropdown

Very simply, I have one dropdown menu dynamically populated with data: 很简单,我有一个动态填充数据的下拉菜单:

SQL Code 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 Code 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 

What I need is another dropdown that is populated with data based on a selection from the first dropdown box. 我需要的是另一个下拉列表,其中包含基于第一个下拉框中的选择的数据。

I am using MySQL, PHP, Javascript and can also (at a push) use jQuery. 我正在使用MySQL,PHP,Javascript,也可以(推动)使用jQuery。 I have no experience in Ajax. 我没有Ajax的经验。

Would anyone be kind enough to point me in the right direction?! 有人会善意地指出我正确的方向吗?!

Thanks in advance, as always, 提前谢谢,一如既往

Homer. 荷马。

First and Best Method (If you have or may have enough option specific data) 第一种和最佳方法(如果您有或可能有足够的选项特定数据)
Use AJAX. 使用AJAX。 It is the easiest way, I think, compared to the other ways to implement the same. 我认为,与实现相同的其他方式相比,这是最简单的方法。 Use Jquery to implement AJAX. 使用Jquery实现AJAX。 It makes AJAX a piece of cake! 它让AJAX变得轻而易举! Here I share my piece of cake for you - 在这里,我为你分享我的一块蛋糕 -

Following is roughly the complete code you need - 以下是您需要的完整代码 -

  • Call a javascript function populateSecondDropdown() on your first select like this - 在你的第一个选择上调用一个javascript函数populateSecondDropdown(),如下所示 -

      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 
  • Define an ajax call inside inside the populateSecondDropdown() function - 在populateSecondDropdown()函数内部定义一个ajax调用 -

     <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> 
    • And finally the query to fetch 2nd dropdown's options in the AJAX processor file fetchOptions.php. 最后是在AJAX处理器文件fetchOptions.php中获取第二个下拉选项的查询。 You can use $_POST['id_option'] here to fetch the options under it. 您可以在此处使用$ _POST ['id_option']来获取其下的选项。 The database query here should fetch the option_id and option_name fields for every option (as expected by the jquery code inside $.each ) and return a json encoded array like this:- 这里的数据库查询应该为每个选项获取option_idoption_name字段(正如$.each的jquery代码所期望的$.each )并返回一个json编码的数组,如下所示: -

       return json_encode(array("subjects" => $resultOfQuery)); 

Second Method (Using only javascript) 第二种方法(仅使用javascript)

  • Fetch all the data for the second dropdown grouped by the field of the first dropdown. 获取按第一个下拉列表字段分组的第二个下拉列表的所有数据。 Eg let's take courses displayed in the first dropdown and subjects under courses displayed in the 2nd 例如,让我们在第一个下拉菜单中显示课程,在第二个下方显示课程

    • Create all the options of the 2nd dropdown. 创建第二个下拉列表的所有选项。 Assign classes equal to the courses while creating the options like this:- 在创建如下选项时分配等于课程的类: -

       $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>"; 
    • Then define onchange="displaySubjectsUnderThisCourse(this);" 然后定义onchange="displaySubjectsUnderThisCourse(this);" for the first dropdown and write this javascript :- 第一次下拉并写下这个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. 这里的基本思想是隐藏/显示选项组,但我的代码可能有错误。

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. 但是,由于没有人能够对未来如此肯定,因此建议始终使用AJAX方法。

There are two methods: 有两种方法:

  • First, you can load all choices for the second select list into a JavaScript array. 首先,您可以将第二个选择列表的所有选项加载到JavaScript数组中。 When an option is selected in the first select, populate the second with the appropriate options. 在第一个选择中选择一个选项时,使用适当的选项填充第二个选项。
  • Second, you can use Ajax to make a call to the server and fetch the options for the second select based on the choice of the first. 其次,您可以使用Ajax调用服务器,并根据第一个选择获取第二个选择的选项。 The server would then return a list of options (one per line, tab delimited is how I do it) that you parse and use to populate the second select. 然后,服务器将返回一个选项列表(每行一个,分隔符是我如何操作),您解析并用于填充第二个选择。

The first option is very fast and easy, but may take a while to load if you have a large list of options for the second select. 第一个选项非常快速和简单,但如果您有第二个选择的大量选项列表,可能需要一段时间才能加载。

The second option is more complicated, but much more flexible. 第二种选择更复杂,但更灵活。

Here's some Ajax code to get you started: 这里有一些Ajax代码可以帮助您入门:

Create a request: 创建请求:

var HTTP_UNINITIALIZED  = 0;
var HTTP_SETUP_NOTSENT  = 1;
var HTTP_PROCESSING     = 2;
var HTTP_PARTIAL_RESULT = 3;
var HTTP_COMPLETE       = 4;

function createRequest()
{
  var request = null;

  try
  {
    request = new XMLHttpRequest();
  }
  catch( failed_once )
  {
    try
    {
      request = new ActiveXObject( "Msxml2.XMLHTTP" );
    }
    catch( failed_twice )
    {
      try
      {
        request = new ActiveXObject( "Microsoft.XMLHTTP" );
      }
      catch( failed_thrice )
      {
        request = null;
      }
    }
  }

  return( request );
}

Send the request: 发送请求:

var request = createRequest();
function doSearch( value )
{
  getURL = "<url to get list>?Value=" + value;

  request.open( "POST", getURL, true );
  request.onreadystatechange = showResults;
  request.send( null );
}

Use the results: 使用结果:

function showResults()
{
  if( request.readyState == HTTP_COMPLETE && request.status == 200 )
  {
    if( request.responseText != "" )
    {
      var lines = request.responseText.split( "\n" );
      for( i = 0 ; i < lines.length ; i++ )
      {
        var parts = lines[i].split( "\t" );
        // populate the second select
      }
    }
  }
}

How you handle the server side portion is up to you. 如何处理服务器端部分取决于您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM