创建和动态填充选择动态

2023-09-10 18:22:41 作者:演不出热情

我有2个表,省和行政区。我想填充选择字段选项,在此基础上省选在另一个选择区名称。各区表有ProvinceID域来引​​用它属于哪个省。我知道这是可行的,我只是不明白。我也想创建和更新新区选择而无需刷新页面。

I have 2 tables, Provinces and Districts. 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. 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.

更新:我写这在PHP和MySQL,使用jQuery尽可能少。

UPDATE: I'm writing it in PHP and MySQL, using jQuery as sparingly as possible.

推荐答案

其实,我想通了这一点,在我自己的使用jQuery和岗位。在主选择,我添加的onchange =getDistricts(),并用这个该功能:

I actually figured this out on my own using jQuery and post. On the primary select, I added onchange="getDistricts()" and used this for that function:

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

然后在handler.php,我有捕捉模式,并运行以下code的情况:

And then in handler.php, I have a case that catches the mode, and runs the following code:

<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.