使用 html 和 php 的动态下拉列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18884713/
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-25 18:24:16  来源:igfitidea点击:

Dynamic drop down list using html and php

javascriptphphtmlhtml-select

提问by franvergara66

I'm learning html and php, I have a mysql DB employees where there is a table called Employees_hired, which stores id, name, department and type of contract. I want to make a drop down list of employees who belong to a type of department and a specific contract type. In the code would be something like:

我正在学习 html 和 php,我有一个 mysql 数据库员工,其中有一个名为 Employees_hired 的表,它存储 ID、姓名、部门和合同类型。我想制作属于某种部门和特定合同类型的员工的下拉列表。在代码中会是这样的:

<html>      
<head>
    <title>Dynamic Drop Down List</title>
</head>
<body>
    <form id="form1" name="form1" method="post" action="<?php $_SERVER['PHP_SELF']?>">
        department: 
        <select id="department" name="department" onchange="run()">  <!--Call run() function-->
            <option value="biology">biology</option>
            <option value="chemestry">chemestry</option>
            <option value="physic">physic</option>
            <option value="math">math</option>     
        </select><br><br>
        type_hire: 
        <select id="type_hire" name="type_hire" onchange="run()">  <!--Call run() function-->
            <option value="internal">Intenal</option>
            <option value="external">External</option>                
        </select><br><br>
        list of employees:
        <select name='employees'>
            <option value="">--- Select ---</option>
            <?php
            mysql_connect("localhost","root","");
            mysql_select_db("employees_hired");
            $list=mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')";);
            while($row_list=mysql_fetch_assoc($list)){
            ?>
            <option value="<?php echo $row_list['name']; ?>">
                <?php if($row_list['name']==$select){ echo $row_list['name']; } ?>
            </option>
            <?php
            }
            ?>
        </select>
    </form> 
</body>
</html>

The question I have is: how to get the selected values ??from the first drop-down lists (type_hire and department) for use in the query and fill the drop down list of employees. I know how to fill a dropdown list by querying the DB (what I learned in an online course) but I do not know how to take the values ??from the dropdown lists and use them in my practice. I read that I can use "document.getElementById (" id "). Value" to give that value to the variable in the query, but nowhere explained in detail how. I am new to web programming and my knowledge of Javascript are poor. Can anyone tell me the best way to do this?. It is possible only using html and php or I have to use javascript?

我的问题是:如何从第一个下拉列表(type_hire 和部门)中获取所选值以用于查询并填充员工的下拉列表。我知道如何通过查询数据库来填充下拉列表(我在在线课程中学到的),但我不知道如何从下拉列表中获取值并在我的实践中使用它们。我读到我可以使用“document.getElementById(“id”)。值”将该值赋予查询中的变量,但没有详细解释如何。我是网络编程的新手,我对 Javascript 的了解很差。谁能告诉我最好的方法来做到这一点?只能使用 html 和 php 还是我必须使用 javascript?

回答by user1056677

So you have the onchange in there and that's a start. The onchange is referencing a JavaScript function that you don't show. There are a couple quick ways to approach this:

所以你有onchange 在那里,这是一个开始。onchange 正在引用您未显示的 JavaScript 函数。有几种快速的方法可以解决这个问题:

  1. Post the form to itself (as you have chosen) or
  2. use ajax (possibly via jQuery for quickness).
  1. 将表单发布到自身(如您所选择)或
  2. 使用 ajax(为了快速起见,可能通过 jQuery)。

(both of these examples don't address how you are accessing the database)

(这两个示例都没有说明您访问数据库的方式)

1)

1)

Using your run function:

使用您的运行功能:

<script type="text/javascript">
     function run(){
          document.getElementById('form1').submit()
     }
</script>

Additional PHP:

额外的PHP:

<?php
    if (isset($_POST['department']) && isset($_POST['type_hire']))
    {
        $value_of_department_list = $_POST['department'];
        $value_of_type_hire = $_POST['type_hire'];

        mysql_connect("localhost","root","");
        mysql_select_db("employees_hired");
        mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')");

        while($row_list=mysql_fetch_assoc($list))
        {
            echo  "<option value=\"{$row_list['name']}\">{$row_list['name']}</option>";
        }
    }
    else
    {
        echo  "<option>Please choose a department and a type of hire</option>";
    }
?>

2)

2)

<script type="text/javascript">
     function run(){
          $.post('get_employees.php',$('form1').serialize(),function(data){

               var html = '';

               $.each(data.employees,function(k,emp){
                   $('select[name="employees"]').append($('<option>', {
                        value: emp.name,
                        text: emp.name
                    }));
               .html(html);
          },"json");
     }
</script>

And get_employees.php would contain something like:

get_employees.php 将包含以下内容:

<?php
if (isset($_POST['department']) && isset($_POST['type_hire']))
{
    $value_of_department_list = $_POST['department'];
    $value_of_type_hire = $_POST['type_hire'];
    $return = array();

    mysql_connect("localhost","root","");
    mysql_select_db("employees_hired");
    mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')");

    while($row_list=mysql_fetch_assoc($list))
    {
        $return[]['name'] = $row_list['name'];
    }

    echo json_encode($return);
}
?>

Note, these are just quickly written examples. A lot more could/should be done here.

请注意,这些只是快速编写的示例。在这里可以/应该做更多的事情。

回答by CP510

Heres a modified jQuery version of your code. (With some cleanup)

这是您的代码的修改 jQuery 版本。(有一些清理)

<html>      
<head>
     <title>Dynamic Drop Down List</title>
</head>
<body>
    <form id="form1" name="form1" method="post" action="<? $_SERVER['PHP_SELF']?>">
        department: 
        <select id="department" name="department" onchange="run()">  
            <!--Call run() function-->
            <option value="biology">biology</option>
            <option value="chemestry">chemestry</option>
            <option value="physic">physic</option>
            <option value="math">math</option>     
        </select><br><br>
        type_hire: 
        <select id="type_hire" name="type_hire" onchange="run()">  
            <!--Call run() function-->
            <option value="internal">Intenal</option>
            <option value="external">External</option>               
        </select><br><br>
        list of employees:
        <select name='employees'>
            <option value="">--- Select ---</option>
            <?php
            mysql_connect("localhost","root","");
            mysql_select_db("employees_hired");
            $list=mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')";);
            while($row_list=mysql_fetch_assoc($list)){
            ?>
            <option value="<?php echo $row_list['name']; ?>">
                <? if($row_list['name']==$select){ echo $row_list['name']; } ?>
            </option>
            <?php
            }
            ?>
        </select>
    </form> 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <!--[ I'M GOING TO INCLUDE THE SCRIPT PART DOWN BELOW ]-->
</body>
</html>

Now I cleaned up the tags, and added a hotlink to jQuery using googleapis free cdn. Next is the actual javascript. Btw. DO NOT USE THE MYSQL_* FUNCTIONS IN PHP. They are depreciated. Check out http://php.net/manual/en/mysqlinfo.library.choosing.phpfor more info on that. On to the scripting...

现在我清理了标签,并使用 googleapis 免费 cdn 添加了一个指向 jQuery 的热链接。接下来是实际的javascript。顺便提一句。不要在 PHP 中使用 MYSQL_* 函数。它们折旧了。查看http://php.net/manual/en/mysqlinfo.library.choosing.php了解更多信息。进入脚本...

<script type="text/javascript">
$('#type_hire').change(function() {
   var selected = $('#type_hire option:selected');  //This should be the selected object
   $.get('DropdownRetrievalScript.php', { 'option': selected.val() }, function(data) {
      //Now data is the results from the DropdownRetrievalScript.php
      $('select[name="employees"]').html(data);
   }
}
</script>

Now I just freehanded that. But I'll try and walk you though it. First we grab the "select" tag that we want to watch (the hashtag means find the element by ID). Then we grab the selected option within that. Next we run a AJAX call to preform a GET on the page "DropdownRetrievalScript.php" which you would create. What that script should do is take the GET variable "option" and run it through the database. Then have it echo out the "option" tags. Our javascript stuff then takes those results and plugs them directly into the select tag with the name attribute of employees.

现在我只是写意。但我会试着陪你走一遍。首先,我们获取我们想要观看的“select”标签(hashtag 表示通过 ID 查找元素)。然后我们抓住其中的选定选项。接下来,我们运行 AJAX 调用以在您将创建的页面“DropdownRetrievalScript.php”上执行 GET。该脚本应该做的是获取 GET 变量“选项”并通过数据库运行它。然后让它回显“选项”标签。然后,我们的 javascript 内容获取这些结果并将它们直接插入到带有员工姓名属性的选择标签中。

Remember that AJAX is just like inputing that url into your browser. So the data variable is literally whatever code or text that url would display. It can be Text, HTML, JSON, XML, anything.

请记住,AJAX 就像在浏览器中输入该 url 一样。所以数据变量实际上就是 url 将显示的任何代码或文本。它可以是文本、HTML、JSON、XML 等等。