通过jquery ajax创建的下拉列表:如何在第一个下拉列表中的第二个下拉列表中获取相关项目

时间:2013-04-03 02:58:07

标签: php jquery ajax

我试图填写第二个下拉列表,但它没有填充过滤器数据,但它根据在第一个下拉列表中选择的国家获取所有状态而不是相关状态请告诉我代码中的错误。无法找到id的值所有状态名称填写在下拉列表中。

               <script type="text/javascript" src="jquery-ajax/jquery.js"></script>
<script>
$(document).ready(function(){             

    $("#country").change(function(){            

        //var optionValue = $("select[name='country_select']").val();      
       var id=$("#country").val(); 
        //var dataString = 'id='+ id;          
          //alert("datastring"+dataString); 

        $.ajax({
            type: "POST",
            url: "getstate.php",
            data: {Country_Id:id},
            beforeSend: function(){ $("#ajaxLoader").show(); },
            complete: function(){ $("#ajaxLoader").hide(); },
            success: function(response){

                $("#stateAjax").html(response);
                $("#stateAjax").show();

        }

        });        
    });

});
</script>

</head>
<?php
include("connection.php");
?>
<body>
<form method="post">
Select Country:<select name="country_select" id="country">
    <option value="">Select Country</option>
<?php
$cntry = mysql_query("SELECT Country_Id, name FROM country ORDER BY name ASC");
while($row = mysql_fetch_array($cntry))
{
    $id=$row['Country_Id'];
    $name=$row['name'];
echo '<option value="'.$id.'">'.$name.'</option>';
}
?>
    </select>
 <span id="errmsg" style="display:none">There is no matching option</span>
  <div id="ajaxLoader" style="display:none"><img src="jquery-ajax/ajax-loader.gif" alt="loading..."></div>
  <div id="stateAjax" style="display:none">
  <select name="state_select" id="state" style="display:none">
  <option value="">Please Select</option></select></select>
  </div>
</form>   
</body>

        getstate.php


    <?php

    echo $_POST['id'];

    include("connection.php");

    $cntry = mysql_query("SELECT * FROM state where country_id=".$_POST['id']);
    ?>
     State: 
    <select name="state_select" id="state">
    <option value="">Please Select</option>
    <?php
    while($row = mysql_fetch_array($cntry))
    {
        $id=$row['State_id'];
        $name=$row['name'];
    echo '<option value="'.$id.'">'.$name.'</option>';

    }

    ?>
    </select>

1 个答案:

答案 0 :(得分:1)

$.ajax({
                type: "POST",
                url: "getstate.php",
                data: {country_id:id},
                ...

编辑1:还

var id=$('#country').val();

编辑2: getstate.php

include("connection.php");

$country_Id = intval($_POST['Country_Id']);//if country_Id is integer...if not:$country_Id = $_POST['Country_Id'];
$cntry = mysql_query("SELECT * FROM state where country_id=".$country_Id);