0

Connection.php 文件,它使用 json 存储数据库连接代码:

<?php
    $username = "root";
    $password = "";
    $database = "roadmap";
    $url = "localhost";

    $con = mysql_connect($url, $username , $password);
    if (!$con) {
       die('Could not connect:' . mysql_error());
    }

    mysql_select_db($database, $con) ;
    $data = array();
    // query your DataBase here looking for a match to $input
    $query = mysql_query("SELECT * FROM students");
    while ($row = mysql_fetch_assoc($query)) {
       $json = array();
       $json['Id'] = $row['Id'];
       $json['Lon'] = $row['Lon'];
       $json['Lat'] = $row['Lat'];
       $data[] = $json;
    }
    header("Content-type: application/json");
    echo json_encode($data);
    mysql_close($con);
?>

在单独的文件 index.php 中:

$.getJSON("connection.php", function(data) {
    addMarker( data[0].Lon,data[0].Lat ,data[0].desc);
    addMarker(-0.13264,51.50918 , );
    addMarker( -0.12498,51.50807 , );
    center = bounds.getCenterLonLat();
    map.setCenter(center, map.getZoomForExtent(bounds) - 1);
    zoom = map.getZoom();   
});

这目前会提取 json 数据,我必须将它用于从数据库中分配零件的每个单独的部分,例如data[0].lon将获得数据库中第一条记录的经度条目。

因为我将与相当多的条目一起工作。我想遍历 json 数组,然后输出所有记录:

addMarker( RECORD 1 );

addMarker( RECORD 2 );

addMarker( RECORD 3 );

谁能帮我这个。

4

3 回答 3

1

使用这样的东西

$.each(data, function(i,row){
  addMarker( row['Lon'],row['Lat'] ,row['desc'])
})
于 2012-10-08T08:31:48.610 回答
0

您可以使用 $.each 循环来迭代您的 json .. 试试这个

试试这个

function(data){

    $.each(data, function(i){

        console.log('Record ' + i + ' : Longitude - ' + data[i].Lon + '  . Latitude  - ' + data[i].Lat + '. Description - ' + data[i].desc    )
    });
}

检查小提琴

于 2012-10-08T08:33:17.410 回答
0

您可以使用 for 循环:

$.getJSON("connection.php", function(data) {
  for(var i = 0; i < data.length; ++i) {
    addMarker(data[i].Lon, data[i].Lat, data[i].desc);
  }
  addMarker(-0.13264,51.50918 , );
  addMarker( -0.12498,51.50807 , );
  center = bounds.getCenterLonLat();
  map.setCenter(center, map.getZoomForExtent(bounds) - 1);
  zoom = map.getZoom();
}); 

或者像其他答案一样使用 jQueryeach函数。

于 2012-10-08T08:36:05.270 回答