如何在没有页面刷新的情况下刷新下拉菜单


How to refresh dropdown without page refresh?

我有以下困难:

我正在从mysql下拉列表中获取值,我希望该信息显示在该下拉列表中。

看到这个:

<select id="location" name="location" class='form-control'>
    <option value="0">Select location</option>
        <?php
            $query = mysql_query("select cityname from city");
                while($row = mysql_fetch_assoc($query))
                {
                    echo '<option value="'.$row['cityname'].'">'.$row['cityname']. '</option>';
                }
        ?>
</select>

通过使用这段代码,我正在填充从数据库到下拉列表的值,但是为此,我需要刷新页面以显示值。

谢谢。

使用jQuery Ajax

yourfile.php

<select id="location" onchange="getState(this.value)" name="location" class='form-control'>
<option value="0">Select location</option>
    <?php
        $query = mysql_query("select * from city");
            while($row = mysql_fetch_assoc($query))
            {
                echo '<option value="'.$row['cityid'].'">'.$row['cityname']. '</option>';
            }
    ?>
</select>
<select id="state">
</select>
Jquery脚本

function getState(city_id)
{
    var html = $.ajax({
        type: "POST",
        url: "path/to/ajax/my_ajax.php",
        data: "city_id=" +city_id,
        async: false
    }).responseText;
    if(html){
        $("#state").html(html);
    }
}

AJAX.php

$query = mysql_query("select * from state where city_id=".$_REQUEST['city_id']);
            while($row = mysql_fetch_assoc($query))
            {
                echo '<option value="'.$row['state_id'].'">'.$row['state_name']. '</option>';
            }