我的代码有问题,我不知道问题是什么。我正在尝试在带有公交车队坐标的地图中移动标记。我的方法是使用PHP和Oracle数据库生成JSON,然后在JavaScript中使用数据来打印标记的移动...但是我认为信息无法传递到Web地图。
请帮忙。
php(marks.php):
query oracle....
while (($row = oci_fetch_array($result, OCI_BOTH)) != false) {
header('Content-Type: application/json');
$data = array($row);
echo json_encode($data);
}
结果:
{"0":"10\/07\/15","MAX(OP.TELEGRAMDATE)":"10\/07\/15","1":"12115","BUSNUMBER":"12115","2":"511031","STOPID":"511031","3":"-765320567","GPSX":"-765320567","4":"33334550","GPSY":"33334550","5":"A11","SHORTNAME":"A11"}
JavaScript:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Real time</title>
<style>
html, body, #map {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places&language=es">
</script>
<script src="http://190.216.202.35/prueba/js/mapmark.js"></script>
</head>
<body >
<div id="map"></div>
</body>
<script>
var map;
map = new google.maps.Map(document.getElementById("map"), {
center : new google.maps.LatLng(3.4404103,-76.5077627),
zoom : 13,
mapTypeId : 'roadmap'
});
$.ajax({
type: "POST",
dataType: "json",
url: "marks.php",
cache: false,
success: function(data){
alert(data[0]); //expected to return value1, but it returns undefined instead.
}
});
</script>
</html>
我正在尝试至少警报数据,但没有任何反应。请帮助我看看我的问题是什么。
最佳答案
您正在获取一个循环,并在每次迭代中输出JSON。那是无效的。您实际上是在生产此代码:
{...}{...}{...}etc...
这是非法的JSON。您需要在循环内部构建一个数组,然后在循环结束后对其进行编码:
$data = array();
while($row = fetch...) {
$data[] = $row;
}
echo json_encode($data);
由于您的JSON非法,因此javascript根本不会对其进行解码(好吧,开始对其进行解码,然后在遇到语法错误时中止)。