【问题标题】:PHP to convert data from query into json arrayPHP将数据从查询转换为json数组
【发布时间】: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


【解决方案1】:

您正在使用 $Lon 并使用 $Lng :

  $Lon = $xml->result->geometry->location->lng;
  $arr[] = array("lat" => $Lat, "lng" => $Lng);

另外,问题标题是错误的:你想要 json 数组,而不是 xml 数组

【讨论】:

  • 谢谢,我没听懂。我对代码进行了更改,但仍然出现错误。
【解决方案2】:

示例代码,请测试。

markers.php

<?php

$p =   [

        ['lat'=>-37.774785, 'lng'=> 145.137978],
        ['lat'=>-37.819616, 'lng'=> 144.968119],
        ['lat'=>-38.330766, 'lng'=> 144.695692],
        ['lat'=>-39.927193, 'lng'=> 175.053218],
        ['lat'=>-41.330162, 'lng'=> 174.865694],
        ['lat'=>-42.734358, 'lng'=> 147.439506],
        ['lat'=>-42.734358, 'lng'=> 147.501315],

      ];

echo json_encode($p);

markers.html

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Marker Clustering</title>
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>

<script>
function initMap() {

       var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 3,
          center: {lat: -28.024, lng: 140.887}
        });

        var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

        var markers = locations.map(function(location, i) {
          return new google.maps.Marker({
            position: location,
            label: labels[i % labels.length]
          });
        });

        // Add a marker clusterer to manage the markers.
        var markerCluster = new MarkerClusterer(map, markers,
            {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
      }

var locations;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
    var arr = JSON.parse(xhr.responseText);
    if(Array.isArray(arr)){
      locations = arr;
    }
  }
}
xhr.open('GET', 'markers.php', true);
xhr.send();

  </script>
  <script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
   <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAkUrEm_U0QWg1QNryI1O5FpB0xAvffJ7I&callback=initMap"></script>
 </body>
</html>

或者两种方法:

markers.php

<?php

$p =   [

        ['lat'=>-37.774785, 'lng'=> 145.137978],
        ['lat'=>-37.819616, 'lng'=> 144.968119],
        ['lat'=>-38.330766, 'lng'=> 144.695692],
        ['lat'=>-39.927193, 'lng'=> 175.053218],
        ['lat'=>-41.330162, 'lng'=> 174.865694],
        ['lat'=>-42.734358, 'lng'=> 147.439506],
        ['lat'=>-42.734358, 'lng'=> 147.501315],

      ];

return json_encode($p);

markers_html.php

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Marker Clustering</title>
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>


<script>
function initMap() {

       var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 3,
          center: {lat: -28.024, lng: 140.887}
        });

        var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

        var markers = locations.map(function(location, i) {
          return new google.maps.Marker({
            position: location,
            label: labels[i % labels.length]
          });
        });

        // Add a marker clusterer to manage the markers.
        var markerCluster = new MarkerClusterer(map, markers,
            {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
      }

var locations = <?=include("markers.php");?>;

  </script>
  <script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
   <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAkUrEm_U0QWg1QNryI1O5FpB0xAvffJ7I&callback=initMap"></script>
 </body>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 2015-07-02
    • 2016-07-07
    • 2013-06-18
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    相关资源
    最近更新 更多