Javascript 根据下拉选择从数据库填充另一个选择下拉

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11636293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:37:25  来源:igfitidea点击:

Populate another select dropdown from database based on dropdown selection

phpjavascriptajax

提问by infinity

I am building a website to learn coding and am trying to build a tool where a user clicks on a select/dropdown that contains some category names pulled from database catand then another select will appear with subcategory names pulled from database subcat. This is almost exactly like Yelp's (go down to the categories) like Yelp's (go down to the categories).

我正在构建一个网站来学习编码,并试图构建一个工具,用户单击包含从数据库cat 中提取的一些类别名称的选择/下拉列表,然后另一个选择将出现,其中包含从数据库subcat 中提取的子类别名称。这几乎与 Yelp's (转到类别)一样,就像 Yelp's (转到类别) 一样

I also made a diagram:

我也做了个图:

enter image description here

在此处输入图片说明

I already have a category dropdown that is pulling from catdatabase:

我已经有一个从cat数据库中提取的类别下拉列表:

<p><b>Category:</b><br />
 <?php
  $query="SELECT id,cat FROM cat";
  $result = mysql_query ($query);
  echo"<select name='cselect3' class='e1'><option value='0'>Please Select A       Category</option>";
  // printing the list box select command
  while($catinfo=mysql_fetch_array($result)){//Array or records stored in $nt
  echo "<option value=\"".htmlspecialchars($catinfo['cat'])."\">".$catinfo['cat']."    </option>";

  }

echo"</select>";
?>

And I have a subcat that is pulling from subcat database:

我有一个从 subcat 数据库中提取的 subcat:

<p><b>Subcat1:</b><br />
<?php
  $query="SELECT id,subcat FROM subcat";
  $result = mysql_query ($query);
  echo"<select name='sselect1' class='e1'><option value='0'>Please Select A Category</option>";
  // printing the list box select command
  while($catinfo=mysql_fetch_array($result)){//Array or records stored in $nt
      echo "<option value=\"".htmlspecialchars($catinfo['subcat'])."\">".$catinfo['subcat']."</option>";

  }

 echo"</select>";
?>

How do I make a subcategory dropdown based on what the user clicks on category and make it automatically appear? Thanks so much for any and all help!

如何根据用户单击类别的内容制作子类别下拉列表并使其自动显示?非常感谢您的任何帮助!

回答by dano

I would just make put the variables in javascript with php and then use javascript functions.. no jquery or AJAX needed.

我只想用 php 将变量放在 javascript 中,然后使用 javascript 函数..不需要 jquery 或 AJAX。

However you need to have a foreign key for subcategories no matter what.. ie - For every record in subcat table you need to give it a catid so for referencing...

但是,无论如何,您都需要为子类别设置外键.. 即 - 对于 subcat 表中的每条记录,您都需要给它一个 catid 以便引用...

<?php
  $db = new mysqli('localhost','user','password','dbname');//set your database handler
  $query = "SELECT id,cat FROM cat";
  $result = $db->query($query);

  while($row = $result->fetch_assoc()){
    $categories[] = array("id" => $row['id'], "val" => $row['cat']);
  }

  $query = "SELECT id, catid, subcat FROM subcat";
  $result = $db->query($query);

  while($row = $result->fetch_assoc()){
    $subcats[$row['catid']][] = array("id" => $row['id'], "val" => $row['subcat']);
  }

  $jsonCats = json_encode($categories);
  $jsonSubCats = json_encode($subcats);


?>

<!docytpe html>
<html>

  <head>
    <script type='text/javascript'>
      <?php
        echo "var categories = $jsonCats; \n";
        echo "var subcats = $jsonSubCats; \n";
      ?>
      function loadCategories(){
        var select = document.getElementById("categoriesSelect");
        select.onchange = updateSubCats;
        for(var i = 0; i < categories.length; i++){
          select.options[i] = new Option(categories[i].val,categories[i].id);          
        }
      }
      function updateSubCats(){
        var catSelect = this;
        var catid = this.value;
        var subcatSelect = document.getElementById("subcatsSelect");
        subcatSelect.options.length = 0; //delete all options if any present
        for(var i = 0; i < subcats[catid].length; i++){
          subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
        }
      }
    </script>

  </head>

  <body onload='loadCategories()'>
    <select id='categoriesSelect'>
    </select>

    <select id='subcatsSelect'>
    </select>
  </body>
</html>

回答by functionvoid

Since the data in your Sub-Category drop down is dependent on what is selected in the category, you probably want to use ajax. You can set an event listener on your category drop down and when it changes you can request the data for the subcategory drop down and populate it, there are many different ways to go about it, below is one option (using jquery) to get you started.

由于子类别下拉列表中的数据取决于类别中选择的内容,因此您可能希望使用 ajax。您可以在类别下拉列表中设置一个事件侦听器,当它发生变化时,您可以请求子类别下拉列表的数据并填充它,有很多不同的方法来处理它,下面是一个选项(使用 jquery)让你开始了。

// warning sub optimal jquery code 
$(function(){

   // listen to events on the category dropdown
   $('#cat').change(function(){

       // don't do anything if use selects "Select Cat"
       if($(this).val() !== "Select Cat") {

           // subcat.php would return the list of option elements 
           // based on the category provided, if you have spaces in 
           // your values you will need to escape the values
           $.get('subcat.php?cat='+ $(this).val(), function(result){
               $('#subcat').html(result);
           });

       }

   });

});

回答by Rupesh Patel

make this html structure on landing page

在登陆页面上制作这个 html 结构

<p><b>Category:</b><br />
 <?php
  $query="SELECT id,cat FROM cat";
  $result = mysql_query ($query);
  echo"<select name='cselect3' onChange='loadSubCats(this.value)' class='e1'><option value='0'>Please Select A       Category</option>";
  // printing the list box select command
  while($catinfo=mysql_fetch_array($result)){//Array or records stored in $nt
  echo "<option value=\"".htmlspecialchars($catinfo['cat'])."\">".$catinfo['cat']."    </option>";

  }

echo"</select>";
?>

<div id='sub_categories'></div>

make a js function assigned to the category dropdown

将js函数分配给类别下拉列表

function loadSubCats(value)
{
  $.post('load_sub_cats.php',{catid : value},function{data}
                                             {
                                              $('#sub_categories').html(data);

                                             });

}

now in your load_sub_cats.php

现在在你的 load_sub_cats.php

<p><b>Subcat1:</b><br />
<?php
  $catid = $_POST['cat_id']
  $query="SELECT id,subcat FROM subcat where catid = $catid";
  $result = mysql_query ($query);
  echo"<select name='sselect1' class='e1'><option value='0'>Please Select A Category</option>";
  // printing the list box select command
  while($catinfo=mysql_fetch_array($result)){//Array or records stored in $nt
      echo "<option value=\"".htmlspecialchars($catinfo['subcat'])."\">".$catinfo['subcat']."</option>";

  }

 echo"</select>";
?>

You will need to include jquery to this code work.

您需要在此代码工作中包含 jquery。

回答by Zack Marrapese

If you are using AJAX, you will want that second bit of code to be a separate php file which you will call via AJAX. in the callback from the AJAX call, just do (pseudo-code): someContainingDivOrSomething.innerHtml = responseBody;.

如果您使用 AJAX,您将希望第二位代码是一个单独的 php 文件,您将通过 AJAX 调用该文件。在 AJAX 调用的回调中,只需执行 (pseudo-code): someContainingDivOrSomething.innerHtml = responseBody;

Note that it's generally a bad idea to do querying within your PHP display files directly (separation of concerns). There are several other things that could be improved. However, this will get you started.

请注意,直接在 PHP 显示文件中进行查询通常是一个坏主意(关注点分离)。还有其他一些可以改进的地方。然而,这会让你开始。