【发布时间】:2017-03-17 13:25:19
【问题描述】:
我有一些代码可以查询我的数据库并返回地址数据。然后我将地址转换为 json 格式的纬度和经度,以便我可以使用 javascript 函数在谷歌地图上显示标记。总体结果是关于 json 数据意外结束的错误代码。我认为问题出在 php 文件中。当我自己运行它时,我得到一个损坏的页面响应。有谁知道我为什么会出错?
这里是php代码:
$address = pg_query($conn, "
SELECT
incident.address,
incident.city,
incident.state_1
FROM
fpscdb001_ws_001.incident
WHERE
incident.initial_symptom = 'Chrome Upgrade' AND
incident.is_installed != 'true';");
if (!$address) {
echo "Query failed\n";
exit;
}
$arr = array();
while ($markers = pg_fetch_row($address)){
$Lat = $xml->result->geometry->location->lat;
$Lon = $xml->result->geometry->location->lng;
$arr[] = array("lat" => $Lat, "lng" => $Lng);
}
echo json_encode($arr);
}
pg_close($conn);
这里是javascript:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var arr = JSON.parse(xhr.responseText);
if(Array.isArray(arr)){
showMarkers(arr);
}
}
}
xhr.open('GET', 'markers.php', true);
xhr.send();
function showMarkers(locations){
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
});
var markerCluster = new MarkerClusterer(map, markers, {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});}}
控制台: 未捕获的 SyntaxError:JSON 输入意外结束 在 JSON.parse() 在 XMLHttpRequest.xhr.onreadystatechange (map.php:36)
【问题讨论】:
-
为什么需要数组?只需传递一个包含两个值的字符串。
-
如果由于您的错误响应不是 JSON 格式而发生错误怎么办?我指的是你在哪里回显
"Query failed\n" -
你能console.log() xhr.responseText 的内容并将结果粘贴到这里吗?
-
我添加了 console.log(arr),但没有显示任何内容。
-
我认为错误发生在 JSON.parse() 方法中,因此 console.log(xhr.responseText) 作为 onreadystatechange 的第一条语句会是一个更好的主意。此外,正如 Ananth Rao 所指出的,如果您的查询失败,您不会返回 JSON,并且您没有在 js 代码中处理
标签: javascript php