动态创建和填充选择

我有2个表,省和区。 我想在一个选择字段中填入选项作为区域名称,根据在另一个选择中选择哪个省。 Districts表有一个ProvinceID字段,用于引用它所属的省份。 我知道这是可行的,我只是想不出来。 我还想创建和更新新的区域选择而不刷新页面。

更新:我用PHP和MySQL编写它,尽可能少地使用jQuery。

为了在没有AJAX的情况下执行此操作,请预先填充Javascript数据集…警告,如果您有大量数据,这可能会很慢,但如果它是一个可管理的列表长度,您可以从加载相同数据的多个AJAX请求中节省一些开销一遍又一遍。

var provinces = {}; provinces['province_a_id'] = [ { name:'District A', id:'district_a_id' }, { name:'District B', id:'district_b_id' } ]; provinces['province_b_id'] = [ { name:'District C', id:'district_c_id' }, { name:'District D', id:'district_d_id' } ]; function getDistricts( referenced_select ) { var selected_province = $(referenced_select).val(); var district_select = $('#districts'); district_select.empty(); if ( provinces[selected_province] ) { $.each( provinces[selected_province], function(i,v) { district_select.append( $(' 

– HTML

   

我实际上是使用jQuery和post自己想出来的。 在主要选择上,我添加了onchange =“getDistricts()”并将其用于该函数:

 function getDistricts() { var province_id = $("#provinces").val(); $.post("handler.php", { "mode" : "get_districts", "pid" : province_id }, function(data) { $("#districts").html(data); }, "text"); } 

然后在handler.php中,我有一个捕获模式的情况,并运行以下代码:

  while($row = $sql->fetchrow($result); { $id = $row['id']; $name = $row['name']; $html .= ""; } echo $html; 

我不是这个解决方案的粉丝,并且真的想要更好的东西,但它确实做了我现在需要做的事情。 我希望这可以帮助其他人。

创建一个php脚本并将其命名为dp.php(dp,data_provider的缩写,使用您喜欢的任何名称)。 在dp.php中

 // get province id passed in via `post` or `get` $pid = $_REQUEST['pid']; // get the districts in that province $query = "SELECT `district_id`, `district` FROM `districts` WHERE province_id` ='$pid'"; // link to your database $link = mysqli_connect(HOST, USER, PASS, DBNAME); // execute your query $result = mysqli_query($link, $query); // parse the options while($row = mysqli_fetch_assoc($result)) { $options .= '\n"; } // send options echo $options 

在页面中使用以下标记:

   

包括以下jQuery:

 // whenever a different province is selected $('#province').change(function() { // remove all options in district select $('#district').html(''); // find the new province selected var my_province = $('#province').val(); // get new options from server and put them in your district select $('#district').get('path/to/dp.php?pid=' + my_province); )}; 

您没有说明您正在使用的服务器端技术(如果有)。 这是ASP.net中的一个示例 – 它应该指向正确的方向:

http://www.mikesdotnetting.com/Article/97/Cascading-DropDownLists-with-jQuery-and-ASP.NET