国家和城市下降

时间:2018-02-20 07:14:54

标签: php jquery mysql ajax

我是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>";


?>

2 个答案:

答案 0 :(得分:0)

更改您的ajax代码:

&#13;
&#13;
   $(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;
&#13;
&#13;

答案 1 :(得分:0)

而不是var s=$(this).val();行  试试

var s=$('#st option:selected').val();

警报(一个或多个);