如何刷新下拉菜单而不刷新页面?

时间:2015-07-08 11:01:05

标签: php mysql

我遇到以下困难:

我从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>

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

谢谢。

1 个答案:

答案 0 :(得分:3)

使用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>';
            }