简体   繁体   English

动态创建和填充选择

[英]Creating and populating a select dynamically

I have 2 tables, Provinces and Districts. 我有2个表格,省和地区。 I would like to populate a select field with options as District names based on which Province is chosen in another select. 我想在选择字段中填充选项作为地区名称,这取决于在另一个选择中选择的省份。 The Districts table has a ProvinceID field to reference which Province it belongs to. Districts表具有一个ProvinceID字段以引用其所属的省。 I know this is doable, I just can't figure it out. 我知道这是可行的,但我只是想不通。 I also want to create and update the new Districts select without refreshing the page. 我也想创建和更新新的所选区,而无需刷新页面。

UPDATE: I'm writing it in PHP and MySQL, using jQuery as sparingly as possible. 更新:我用PHP和MySQL编写它,尽可能少用jQuery。

In order to do it without AJAX, prepopulate a Javascript dataset... warning, if you have a lot of data this could be slow, but if it's a manageable list length, you could save some overhead from multiple AJAX requests loading the same data over and over. 为了在没有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( $('<option value="' + v['id'] + '">').text( v['name'] ) );
    } );
  }
}

$(document).ready( function() {
  $('#provinces').bind( 'change', function() {
    getDistricts(this);
  } );
} );

-- HTML -HTML

<select id="provinces" name="provinces">
  <option value="province_a_id">Province A</option>
  <option value="province_b_id">Province B</option>
</select>
<select id="districts" name="districts">
</select>

Make a php script and call it dp.php ( dp, short for data_provider, use any name you like). 创建一个php脚本并将其命名为dp.php(dp,data_provider的缩写,使用您喜欢的任何名称)。 In dp.php 在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 .= '<option value="' . row['district_id'] . '">' . $row['district'] . "</option>\n";
}

// send options
echo $options

With the following markup in your page: 在页面中添加以下标记:

<select id="province" name="province">
  <option value="ny">New York</option>
  ...
</select>

<select id="district" name="district">
</select>

Include the following jQuery: 包括以下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);
)};

You didn't state what server side technology you are using (if any). 您没有说明正在使用的服务器端技术(如果有)。 Here's an example in ASP.net - it should point you in the right direction: 这是ASP.net中的一个示例-它应该为您指明正确的方向:

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

I actually figured this out on my own using jQuery and post. 我实际上是使用jQuery和post自己弄清楚的。 On the primary select, I added onchange="getDistricts()" and used this for that function: 在主要选择中,我添加了onchange =“ getDistricts()”并将其用于该功能:

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

And then in handler.php, I have a case that catches the mode, and runs the following code: 然后在handler.php中,我有一个捕捉模式的案例,并运行以下代码:

<query on districts table>
while($row = $sql->fetchrow($result);
{
    $id = $row['id'];
    $name = $row['name'];
    $html .= "<option value='$id' id='$id'>$name</option>";
}
echo $html;

I'm not a fan of this solution, and would really like something better, but it does what I need it to do for the moment. 我不喜欢这种解决方案,并且确实希望有更好的解决方案,但是它确实满足了我目前需要做的事情。 I hope this can help someone else out. 我希望这可以帮助其他人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM