如何通过从另一个下拉列表中选择值来填充下拉列表?

时间:2022-10-17 14:12:41

I have build two drop downs (like state and city) by fetching the records of both drop downs from mysql database and am trying to build the tool in which, while selecting any value (i.e. any state) from first drop down, at that time in second drop down (in city) only those values (cities) under that value (state) selected in first drop down should be visible.

我通过从mysql数据库中获取两个下拉列表的记录来构建两个下拉(如州和城市),并且我正在尝试构建工具,在此时从第一个下拉列表中选择任何值(即任何状态)在第二次下拉(在城市中)中,只有那些在第一个下拉列表中选择的值(州)下的值(城市)应该是可见的。

Here's my code:

这是我的代码:

<tr>    
        <td id='hed'><span style="font-family:verdana,geneva,sans-  serif">State</state></td>
        <td>
        <?php 
        $dbcon = mysql_connect("@ip","@username","@password");

        if($dbcon)
        {
            mysql_select_db("@database", $dbcon);
        }
        else
        {
            die('error connecting to the database');
        }

        $qry = "select @value(state) from @tablename  ";
        $result = mysql_query($qry) or die(mysql_error());

        $dropdown = "<select name='@valuename' id='officeItemList' style='cursor:pointer;cursor:hand;'>";
        while($row = mysql_fetch_array($result))
        {           
            $dropdown .= "\r\n<option value='{$row['@value']}' > {$row['@value']} </option>";
        }
        $dropdown .= "\r\n</select>"; 
        echo $dropdown;
        mysql_close($dbcon);
        ?>
        </td> 
    </tr>

        <tr>
        <td id='hed'><span style="font-family:verdana,geneva,sans-serif">City</span></td>
        <td colspan="1"> 
        <?php 
        $dbcon = mysql_connect("@ip","@username","@password");

        if($dbcon)  
        {
            mysql_select_db("@database", $dbcon);
        }  
        else
        {
            die('error connecting to the database');
        }  

        $qry = "select value2(city) from @tablename where ";
        $result = mysql_query($qry) or die(mysql_error()); 

        $dropdown = "<select name='@value2' id='officeItemList' style='cursor:pointer;cursor:hand;'>";
        while($row = mysql_fetch_array($result)) 
        {

            $dropdown .= "\r\n<option value='{$row['@value2']}' > {$row['@value2']} </option>";
        }
        $dropdown .= "\r\n</select>"; 
        echo $dropdown;
        mysql_close($dbcon);
        ?>      


        </td>
    </tr>

4 个解决方案

#1


3  

You can use AJAX to fetch the cities for the selected state. Something like:

您可以使用AJAX来获取所选州的城市。就像是:

$("select#state").change(
function(){
   var state = $(this).val();
   $.ajax({
  type: "GET",
  url: "get_cities.php/?state=" + state, 
// write a query according to the state selected and return the HTML for the OPTION's
  success: function(cities){
    $("select#cities").html(cities);
   }
}); 
}
);

You can also return a json object (in which case don't forget to add dataType:"json") and make the transition to HTML in the client-side, i.e inside the success function

你也可以返回一个json对象(在这种情况下不要忘记添加dataType:“json”)并在客户端转换为HTML,即在success函数内部

#2


6  

That is the wrong way. Your PHP code is fully executed before showing the page to user. So second query can never know that user choses something.

这是错误的方式。在向用户显示页面之前,您的PHP代码已完全执行。所以第二个查询永远不会知道用户选择了什么。

Right way #1: Do it in two pages. First page contains first combo and when it is submitted second page is generated and shows the second combo.

正确的方法#1:两页做。第一页包含第一个组合,当它被提交时,第二页生成并显示第二个组合。

Right way #2 although not optimal: Do it in one page. Load all possible records for second combo to some JS array. Place listener to first array. When user choses something fill second combo with right records from JS-array.

正确的方式#2虽然不是最佳的:在一页中做。将第二个组合的所有可能记录加载到某个JS数组。将侦听器放在第一个数组中。当用户选择使用JS-array中的正确记录填充第二个组合时。

Right way #3 (most right of them): Do it in a page with AJAX-request in it. User selects a value in the first combo. Its listener sends a request to some server script which returns JSON-object with records for second combo.

正确的方式#3(最右边的):在包含AJAX请求的页面中进行。用户在第一个组合中选择一个值。它的侦听器向某个服务器脚本发送请求,该脚本返回带有第二个组合记录的JSON对象。

#3


1  

There are 2 approaches i would suggest to you.

我建议你有两种方法。

First one only uses php but needs to store all available cities per state before the page is rendered. This is a bad solution!

第一个只使用php但需要在呈现页面之前存储每个州的所有可用城市。这是一个糟糕的解决方案!

I would suggest using AJAX and a Javascript call to another PHP Script can solve your problem!

我建议使用AJAX和Javascript调用另一个PHP脚本可以解决您的问题!

Use jQuery to get a javascript framework that makes live easier!

使用jQuery获得一个让生活更轻松的javascript框架!

Your HTML:

你的HTML:

<select id="select-state">
    <option value="0">Select a state</option>
    <option value="ohio">Ohio</option>
</select>
<select id="select-city">
    <option value="0">Select a state first</option>
</select>

Create a php script that makes the mysql query with a given state via $_GET["state"] (or $_POST).

创建一个php脚本,通过$ _GET [“state”](或$ _POST)使mysql查询具有给定状态。

Encode the result from mysql as a JSON Object and echo it!

将mysql中的结果编码为JSON对象并回显它!

{
    cities: [
        'City 1',
        'City 2',
        ...
    ]
}

php function: json_encode()

php函数:json_encode()

You then can do someting like:

然后你可以做一些像:

$(function(){
    $('#select-state').on("change", function(){
        var state = $(this).val();
        if(state!=0) {
            $.get('your/path/to/cities/script.php?state='+state,function(data){
                if(data.cities) {
                    $('#select-city').empty(); //remove old entries first
                    for (var city in data.cities) {
                        $option = $('<option>').val(city);
                        $('#select-city').append($option);
                    }
                } 
            });
        }
    });
});

#4


0  

Three quick points:

三个快速点:

  1. mysql is unsafe (you should use PDO or mysqli instead)
  2. mysql不安全(你应该使用PDO或mysqli)
  3. Style should be specified with CSS, not inline
  4. 样式应使用CSS指定,而不是内联
  5. You'd better using an asynchronous request, so the user experience feels quickier
  6. 您最好使用异步请求,这样用户体验会更快捷

Note that all of the three points above are easily achievable by using a framework (at least on the client side, like CakePHP or Zend, but you can also look for a Javascript one like Knockout.js for the UI interactions)

请注意,通过使用框架(至少在客户端,如CakePHP或Zend,可以轻松实现上述所有三点,但您也可以查找类似于Knockout.js的Javascript以进行UI交互)

#1


3  

You can use AJAX to fetch the cities for the selected state. Something like:

您可以使用AJAX来获取所选州的城市。就像是:

$("select#state").change(
function(){
   var state = $(this).val();
   $.ajax({
  type: "GET",
  url: "get_cities.php/?state=" + state, 
// write a query according to the state selected and return the HTML for the OPTION's
  success: function(cities){
    $("select#cities").html(cities);
   }
}); 
}
);

You can also return a json object (in which case don't forget to add dataType:"json") and make the transition to HTML in the client-side, i.e inside the success function

你也可以返回一个json对象(在这种情况下不要忘记添加dataType:“json”)并在客户端转换为HTML,即在success函数内部

#2


6  

That is the wrong way. Your PHP code is fully executed before showing the page to user. So second query can never know that user choses something.

这是错误的方式。在向用户显示页面之前,您的PHP代码已完全执行。所以第二个查询永远不会知道用户选择了什么。

Right way #1: Do it in two pages. First page contains first combo and when it is submitted second page is generated and shows the second combo.

正确的方法#1:两页做。第一页包含第一个组合,当它被提交时,第二页生成并显示第二个组合。

Right way #2 although not optimal: Do it in one page. Load all possible records for second combo to some JS array. Place listener to first array. When user choses something fill second combo with right records from JS-array.

正确的方式#2虽然不是最佳的:在一页中做。将第二个组合的所有可能记录加载到某个JS数组。将侦听器放在第一个数组中。当用户选择使用JS-array中的正确记录填充第二个组合时。

Right way #3 (most right of them): Do it in a page with AJAX-request in it. User selects a value in the first combo. Its listener sends a request to some server script which returns JSON-object with records for second combo.

正确的方式#3(最右边的):在包含AJAX请求的页面中进行。用户在第一个组合中选择一个值。它的侦听器向某个服务器脚本发送请求,该脚本返回带有第二个组合记录的JSON对象。

#3


1  

There are 2 approaches i would suggest to you.

我建议你有两种方法。

First one only uses php but needs to store all available cities per state before the page is rendered. This is a bad solution!

第一个只使用php但需要在呈现页面之前存储每个州的所有可用城市。这是一个糟糕的解决方案!

I would suggest using AJAX and a Javascript call to another PHP Script can solve your problem!

我建议使用AJAX和Javascript调用另一个PHP脚本可以解决您的问题!

Use jQuery to get a javascript framework that makes live easier!

使用jQuery获得一个让生活更轻松的javascript框架!

Your HTML:

你的HTML:

<select id="select-state">
    <option value="0">Select a state</option>
    <option value="ohio">Ohio</option>
</select>
<select id="select-city">
    <option value="0">Select a state first</option>
</select>

Create a php script that makes the mysql query with a given state via $_GET["state"] (or $_POST).

创建一个php脚本,通过$ _GET [“state”](或$ _POST)使mysql查询具有给定状态。

Encode the result from mysql as a JSON Object and echo it!

将mysql中的结果编码为JSON对象并回显它!

{
    cities: [
        'City 1',
        'City 2',
        ...
    ]
}

php function: json_encode()

php函数:json_encode()

You then can do someting like:

然后你可以做一些像:

$(function(){
    $('#select-state').on("change", function(){
        var state = $(this).val();
        if(state!=0) {
            $.get('your/path/to/cities/script.php?state='+state,function(data){
                if(data.cities) {
                    $('#select-city').empty(); //remove old entries first
                    for (var city in data.cities) {
                        $option = $('<option>').val(city);
                        $('#select-city').append($option);
                    }
                } 
            });
        }
    });
});

#4


0  

Three quick points:

三个快速点:

  1. mysql is unsafe (you should use PDO or mysqli instead)
  2. mysql不安全(你应该使用PDO或mysqli)
  3. Style should be specified with CSS, not inline
  4. 样式应使用CSS指定,而不是内联
  5. You'd better using an asynchronous request, so the user experience feels quickier
  6. 您最好使用异步请求,这样用户体验会更快捷

Note that all of the three points above are easily achievable by using a framework (at least on the client side, like CakePHP or Zend, but you can also look for a Javascript one like Knockout.js for the UI interactions)

请注意,通过使用框架(至少在客户端,如CakePHP或Zend,可以轻松实现上述所有三点,但您也可以查找类似于Knockout.js的Javascript以进行UI交互)