weixin_33724046 2016-09-03 16:23 采纳率: 0%
浏览 110

如何在Ajax中循环

I want to display all of my markers stored in the database. I want to use ajax to retrieve all the markers` latitude and longitude in my database and use it to display the markers in the map.How to loop in ajax?

$.ajax({
  url: 'php_action/map/fetchmarker.php',
  dataType: 'json',
  success:function(response) 
  { 
     var plate = response[1];
     map.addMarker({
        lat: response[2],
        lng: response[3],
        title: plate

      });
   }
   });

fetchmarker.php

       <?php 
  $sql = "SELECT t_id,b.b_platenum,t_lat,t_long from tbltrackbus as a inner join tblbusdesc as b on a.t_bid=b.b_id";
  $result = $connect->query($sql);

 if($result->num_rows > 0) { 
$row = $result->fetch_array();
} // if num_rows

 echo json_encode($row);
?>
  • 写回答

1条回答 默认 最新

  • weixin_33725270 2016-09-03 16:55
    关注
    if($result->num_rows > 0) { 
        $row = $result->fetch_array();
    }
    
    echo json_encode($row);
    

    The above will only output the first result, and if there aren't any results it will output nothing, throwing an error.

    You need to have something to loop over before you can perform the loop you are asking about.

    You need to create an array and put all the results in it. Then output that array.

    $output = [];
    while ($row = $result->fetch_array()) {
        $output[] = $row;
    }
    echo json_encode($output);
    

    Once you do that, response will be an array of arrays which you can loop over.

    success: function(response) {
        for (var i = 0; i < response.length; i++) {
            var row = response[i];
                var plate = row[1];
                map.addMarker({
                    lat: row[2],
                    lng: row[3],
                    title: plate
    
                });
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等