简体   繁体   English

与ajax和json的依赖下拉列表

[英]dependent dropdown with ajax and json

i am trying to create dependent drop-down field in php. 我试图在php中创建相关的下拉字段。 Everything going well, even it shows printed array value but json returned value does not print on second dropdown list. 一切进展顺利,即使它显示了已打印的数组值,但json返回的值也不会打印在第二个下拉列表上。 Could you suggest me what should i do ? 你能建议我该怎么办?

        <?php
        $id=$_GET["id"];
        $stmt = $conn->prepare("SELECT  Id, Title FROM category where DestId='$id' ");
        //$stmt->bindValue(1,$_GET["id"]);

        // Fetch the foods using the group id
        if ($stmt->execute()) {
            $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
            echo "<pre>".print_r($result)."</pre>";


            // If there are results, json encode them as the reply.
            if ($result) {
                echo json_encode($result);
            }
        }


?>

<div class="tripsearch">
  <h2>Rechercher un voyage !</h2>
  <form id="form1" name="form1" action="<?php echo URL_PATH.'search.php';?>" method="get">
            <select name="destination" id="destination" class="inputBox">
                  <option value="" selected="selected">Destinations</option>
                  <?php $dest_stmt = $conn->prepare("SELECT Id, Title FROM destinations");
                  $dest_stmt->execute();
                  while ($dest_rows = $dest_stmt->fetch()){
                      echo "<option value=\"".$dest_rows['Id']."\">".$dest_rows['Title']."</option>";
                  }
                  ?>                  
            </select>
       <select name="category" id="category"  class="inputBox">
                  <option value="any" selected="selected">Nos activit&eacute;s</option>
      </select>
    <input type="submit" id="search-btn" class="btn btn-org" value="OK" />
  </form>
</div>


<script language="javascript">
    $("#destination").change(function() {
        var Id = $(this).val();
        //alert(Id);

        $.ajax({
            type: "GET",
            //url: "http://192.168.1.120/current-projects/odysseenepaltrekking.com/include/search.php",
            data: { id: Id },
            dataType: "json"
        }).done(function(result) {
            // Clear options
            //$("#category").find("option").remove();
            // Loop through JSON response
            $.each(result, function(key, value) {   
                $('#category').append($('<option>', { value: value.Id }).text(value.Title));

            });
        });

    });
</script>

尝试

$('#category').append('<option value='+value.Id+'>'+value.Title+'</option>');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM