如何在不刷新页面的情况下刷新下拉列表?
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>
通过使用此代码,我将值从数据库填充到下拉列表,但为此我需要刷新页面才能显示值。
谢谢。
使用jQueryAjax
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>';
}
我遇到了以下困难:
我正在从 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>
通过使用此代码,我将值从数据库填充到下拉列表,但为此我需要刷新页面才能显示值。
谢谢。
使用jQueryAjax
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>';
}