基于另一个下拉菜单填充下拉菜单的最佳和最简单的方法是什么

发布于 2024-09-16 21:49:57 字数 1044 浏览 1 评论 0 原文

很简单,我有一个动态填充数据的下拉菜单:

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 

我需要的是另一个下拉菜单,它根据第一个下拉列表中的选择填充数据盒子。

我正在使用 MySQL、PHP、Javascript,也可以(立即)使用 jQuery。我没有 Ajax 经验。

有人能好心地指出我正确的方向吗?

一如既往,提前感谢荷马

Very simply, I have one dropdown menu dynamically populated with data:

SQL Code

$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

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. I have no experience in Ajax.

Would anyone be kind enough to point me in the right direction?!

Thanks in advance, as always,

Homer.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

碍人泪离人颜 2024-09-23 21:49:57

第一个也是最好的方法(如果您有或可能有足够的选项特定数据)
使用 AJAX。我认为,与其他实现相同方法的方法相比,这是最简单的方法。使用Jquery实现AJAX。它使 AJAX 变得小菜一碟!在这里,我为您分享我的小菜一碟 -

以下是您需要的大致完整代码 -

  • 在您的第一个选择上调用 JavaScript 函数 populateSecondDropdown() ,如下所示 -

     echo "";// 关闭列表框 
    
  • 在 populateSecondDropdown() 函数内部定义 ajax 调用 -

    
    
    <脚本类型=“text/javascript”>  
        函数 populateSecondDropdown(对象,baseUrl)
        {
            $.ajax({
            类型:“帖子”, 
            url: baseUrl+"/ajax/fetchOptions.php", 
            数据: { id_option: $(object).val(), 操作: 'get_subjects' },
            数据类型:“json”,
            成功:函数(数据) 
            {
                //清除与第一个下拉列表的较早选项相对应的选项
               $('select#secondDropdown').empty(); 
               $('select#secondDropdown').append('<选项值=“0”>选择选项');
                       //填充第二个下拉菜单的选项
               $.each( 数据. 主题, 函数() 
               {    
                   $('select#secondDropdown').append('<选项值="'+$(this).attr('option_id')+'">'+$(this).attr('option_name')+ '');
               });
               $('select#secondDropdown').focus();
            },
                发送前:函数() 
                {
                    $('select#secondDropdown').empty();
                    $('select#secondDropdown').append('<选项值=“0”>正在加载...');
                },
                错误:函数() 
               {
                  $('select#secondDropdown').attr('已禁用', true);
                  $('select#secondDropdown').empty();
                   $('select#secondDropdown').append('<选项值=“0”>无选项');
              }
            });
         }
    
    
    • 最后是在 AJAX 处理器文件 fetchOptions.php 中获取第二个下拉列表选项的查询。您可以在此处使用 $_POST['id_option'] 来获取其下的选项。这里的数据库查询应该获取每个选项的 option_idoption_name 字段(正如 $.each 中的 jquery 代码所期望的那样)并返回像这样的 json 编码数组:-

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

第二种方法(仅使用 javascript)

  • 获取按第一个下拉列表的字段分组的第二个下拉列表的所有数据。例如,让我们学习第一个下拉列表中显示的课程和第二个下拉列表中显示的课程下的科目

    • 创建第二个下拉列表的所有选项。在创建如下选项时分配与课程相同的班级:-

      $querycourse = "从科目中选择课程、科目,其中科目不为空 GROUP BY 课程";
      $procc = mysqli_prepare($link, $querycourse);
      $queryc = mysqli_query($link, $querycourse) 或 die(mysqli_error($link));
      
      echo "<选择 name='subjects[]' value='' multiple='multiple' size=100>";
      echo "<选项值=''>全部";
                  while($ntc=mysqli_fetch_array($queryc))
                  {//$nt中存储的数组或记录
                      echo "<选项值=\"$ntc[主题]\" class=\"$ntc[课程]\">\"$ntc[主题]\"";
                  }
                  echo "";
      
    • 然后为第一个下拉列表定义 onchange="displaySubjectsUnderThisCourse(this);" 并编写以下 javascript :-

       函数 displaySubjectsUnderThisCourse(object)
       {
           var selectedCourse = $(object).val();
          //显示类别=从第一个下拉列表中选择的选项的选项
          $("."+selectedCourse).removeClass("隐藏"); //定义一个隐藏类,使用display:none;
      
         $('选项:not(.selectedCourse)').hide(); // 隐藏其类不是 selectedCourse 的所有选项 - 但不确定这是否有效
      
        //取消之前的选择
        //如果允许单选项选择
        $('select#secondDropdown 选项').attr('已选择', false); 
        // 如果允许多重选择,则跟随以下内容(IE 需要)
        $('select#secondDropdown 选项').attr('selectedIndex', -1); 
      
      
      }
      

      这里的基本思想是隐藏/显示选项组,但我的代码可能有错误。

最后,请注意,只有当您的数据量有限并且非常确定将来数据总是会更少时,第二种方法(获取所有选项值)才会更好。但是,由于没有人能够对未来如此确定,因此建议始终使用 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 -

  • 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 
    
  • 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>
    
    • 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 and option_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));
      

Second Method (Using only javascript)

  • 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

    • 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);" 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.

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.

不离久伴 2024-09-23 21:49:57

有两种方法:

  • 第一种,您可以加载所有选择
    将第二个选择列表放入
    JavaScript 数组。当一个选项是
    在第一个选择中选择,
    填充第二个
    适当的选择。
  • 其次,你可以使用Ajax来制作一个
    调用服务器并获取
    第二个选择的选项基于
    关于第一个的选择。这
    然后服务器将返回一个列表
    选项(每行一个,制表符分隔
    我就是这样做的)你解析并
    用于填充第二个选择。

第一个选项非常快速且简单,但如果您有大量用于第二个选择的选项,则可能需要一段时间才能加载。

第二种选择更复杂,但更灵活。

下面是一些可以帮助您入门的 Ajax 代码:

创建请求:

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 );
}

发送请求:

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

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

使用结果:

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
      }
    }
  }
}

如何处理服务器端部分由你决定。

There are two methods:

  • First, you can load all choices for
    the second select list into a
    JavaScript array. 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. 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:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文