我是Ajax和PHP的新手,遇到了州和城市动态下降的问题。虽然我已经在stackOverflow中检查了很多答案,但是我无法清楚地了解如何成功编写代码以获得所需的结果。
country_back.php
[Dynamically generates a drop down for states using country_id
]
<?php
$con_id=$_POST['id'];
$con=mysqli_connect("localhost","root","","countries");
$data=mysqli_query($con,"select * from states where country_id='$con_id' ");
echo "<select id='st'>";
while($row=mysqli_fetch_array($data))
{
echo "<option value=".$row['id'].">".$row['name']."</option>";
}
echo "</select>";
?>
ajax file
$("#st").change(function(){
var s=$(this).val();
alert(s); //no value being shown with alert.
$.ajax=({
url:"state_back.php",
method:"post",
data:{stid:s},
dataType:"html",
success:function(strMsg){
$("#city").html(strMsg);
}
})
})
HTML Form
<form method="post">
<div id="city">
<select>
<option>Cities</option>
</select>
</div>
</form>
state_back.php
Dynamically generates a drop down for cities using state_id
<?php
$stid=$_POST['stid'];
$con=mysqli_connect("localhost","root","","countries");
$data=mysqli_query($con,"select * from cities where state_id='$stid' ");
echo "<select>";
while($row=mysqli_fetch_array($data))
{
echo "<option>".$row['name']."</option>";
}
echo "</select>";
?>
答案 0 :(得分:0)
更改您的ajax代码:
$(document).on('change', '#st', function(e){
var s=$('#st').val();
alert(s); //no value being shown with alert.
$.ajax({
url:"state_back.php",
method:"post",
data:{stid:s},
dataType:"html",
success:function(strMsg){
alert(strMsg);
$("#city").html(strMsg);
}
});
});
&#13;
答案 1 :(得分:0)
而不是var s=$(this).val();
行
试试
var s=$('#st option:selected').val();
警报(一个或多个);