国家州下降

时间:2018-02-20 05:30:05

标签: php jquery mysql ajax

我是Ajax和PHP的新手,遇到了国家和州的动态下降问题。 虽然我已经在stackOverflow中检查了很多答案但是我无法清楚地了解我们应该如何成功编码以获得所需的结果。

country.php

<form method="post">

<select id="cont">
<option>Select</option>
<?php
$con=mysqli_connect("localhost","root","","countries");
$data=mysqli_query($con,"select * from countries");
while($row=mysqli_fetch_array($data))
{
    echo "<option class='con' value=".$row['id'] .">".$row['name']."</option>"; 
}
?>
</select>

<div id="states">
<select>
<option>Select</option>
</select>
</div>

</form>

ajax file

$(document).ready(function(){

    $("#cont").change(function(){
        var c=$(this).val();
        $.ajax({
            url:"country_back.php",
            method:"post",
            data:{id:c},
            dataType:"html",
            success:function(strMsg){
                ("#states").html(strMsg);
                }

            })

        })

    })

country_back.php [获取状态数据]

<?php
$con_id=$_POST['id'];
$con=mysqli_connect("localhost","root","","countries");
$data=mysqli_query($con,"select * from states where country_id='$con' ");
echo "<select>";
while($row=mysqli_fetch_array($data))
{
    echo "<option value=".$row['name']."</option>"; 
}
echo "</select>";

?>

1 个答案:

答案 0 :(得分:1)

在你的ajax中:

$(document).ready(function(){

    $("#cont").change(function(){
        var c=$(this).val();
        $.ajax({
            url:"country_back.php",
            method:"post",
            data:{id:c},
            dataType:"html",
            success:function(strMsg){
                alert(strMsg);
                $("#states").html(strMsg);
                }

            })

        })

    })

PHP代码:

<?php
 $con_id=$_POST['id'];
 $con=mysqli_connect("localhost","root","","countries");
 $data=mysqli_query($con,"select * from states where country_id='$con_id' ");  //You should use $con_id
 echo "<select>";
 while($row=mysqli_fetch_array($data))
   {
     echo "<option value=".$row['name'].">".$row['name']."</option>"; 
   }
 echo "</select>";

  ?>

进行更改