如何在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);
?>
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

            });
    }
}