doujiu3882 2017-07-18 04:20
浏览 46
已采纳

从php发送数组到AJAX响应

I am trying to filter state, zones of Nepal using ajax. I have got them in MySQL database.

I have populated zone select box initially, it is okay.

<select class="district col-md-3 center-block" id="zone">
<?php 
    while ($res = mysqli_fetch_assoc($result_zones)) {
        echo "<option value='".$res['name']."'>".$res['name']."</option>";
    }
?>
</select>

Now What I am trying is when user changes zone, I need all districts associated with this zone from districts table.

What I have done is here:

Ajax call

<script>
        $(document.body).on("change","#zone",function(){
            //console.log(this.value);
            $.ajax({
                dataType : 'json',
                async: false,
                url:'process.php?zone_id=' + this.value,
                complete: function (response) {
                    var result = JSON.stringify(response.data);//parsing status from response received from php
                    console.log(result);
                }
               });
        });
</script>

process.php

<?php 
    if (isset($_GET['zone_id'])) {
      $arr =array();
      $zone_id=$_GET['zone_id'];
      $i=0;
      $result = mysqli_query($dbconfig,"SELECT * FROM districts WHERE zone_id = '$zone_id'");
      while ($row = mysqli_fetch_assoc($result)) {
        $arr[$i] = $row;
        $i++;
      }
      // preparing correct format for json_encode
      header('Content-type: application/json'); 
      echo json_encode(array('data' => $arr)); //sending response to ajax
    }
 ?>

When I go through url http://localhost/nepal-locations/process.php?zone_id=8, I'm getting data as I need like below:

{"data":[{"id":"42","name":"Mustang","zone_id":"8"},{"id":"43","name":"Myagdi","zone_id":"8"},{"id":"44","name":"Parbat","zone_id":"8"},{"id":"45","name":"Baglung","zone_id":"8"}]}

But I'm getting data empty in console.

{data: []}
data
:
[]

What might be wrong I'm doing?

Update: output console.log(response) enter image description here

  • 写回答

2条回答 默认 最新

  • donglian1953 2017-07-18 04:40
    关注

    You are getting empty array because you are passing name instead of id

    change your <select> as below:

    <select class="district col-md-3 center-block" id="zone">
    <?php 
        while ($res = mysqli_fetch_assoc($result_zones)) {
            echo "<option value='".$res['id']."'>".$res['name']."</option>"; //<-----Add id instead of name
        }
    ?>
    </select>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置