2016-08-03 24 views
0

我試圖構建一個應用程序,它從數據庫(mysql)獲取用戶數據(lat,lon),然後在Google地圖上顯示它們的位置。在谷歌地圖中顯示JSON響應

下面是代碼示例:

function initMap() { 
     var mapDiv = document.getElementById('map'); 
     var map = new google.maps.Map(mapDiv, { 
     center: {lat: 33.7167, lng: 73.0667}, 
     zoom: 11 
    }); 

    makeRequest('get_locations.php', function(data) { 
     //alert("abc"); 
     var data = JSON.parse(data.responseText); 
     //window.alert(data); 

     for (var i = 0; i < data.length; i++) { 
      //display(data[i]); 
      displayLocation(data[i]); 
     } 
    }); 
} 


function makeRequest(url, callback) { 
    var request; 
    if (window.XMLHttpRequest) { 
     request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari 
    } else { 
     request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5 
    } 
    request.onreadystatechange = function() { 
     if (request.readyState == 4 && request.status == 200) { 
      callback(request); 
     } 
    } 
    request.open("GET", url, true); 
    request.send(); 
} 

get_locations.php

<?php 
    include('connection.php'); 
    $l= array(); 
    $result = mysqli_query($con,"SELECT * FROM users"); 
    while ($row = mysqli_fetch_assoc($result)) { 
     $l[] = $row; 
    } 
    $j = json_decode($l, true); 
    //echo $j; 

?> 

有些事情,我試圖找到代碼中的問題,但未能

  1. 在echo $ j上的get_location.php;它顯示我正確的迴應

  2. 在此行之前var data = JSON.parse(data.responseText);警報(「abc」)的作品,但不是在此之後,所以我認爲這個問題居住在這條線,但不知道爲什麼發生, 任何想法?

+0

在'get_location.php'你需要使用'json_encode'而不是' json_decode',你也需要回顯它,所以ajax回調函數可以使用。 – RamRaider

+0

哦,我怎麼會想念這個?順便說一句,謝謝你的迴應:)它的工作 –

回答

0

我認爲主要的問題是在您需要相反的情況json_decode濫用,json_encode

function initMap() { 
     var mapDiv = document.getElementById('map'); 
     var map = new google.maps.Map(mapDiv, { 
     center: {lat: 33.7167, lng: 73.0667}, 
     zoom: 11 
    }); 

    makeRequest('get_locations.php', function(data) { 
     if(data){ 
      var data = JSON.parse(data); 
      for(var n in data){ 
       var obj=data[ n ]; 

       console.log('%o', obj); 
       displayLocation.call(this,obj); 
      } 
     } 
    }); 
} 


function makeRequest(url, callback) { 
    var request; 
     request = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); 

    request.onreadystatechange = function() { 
     if (request.readyState == 4 && request.status == 200) { 
      callback(request.responseText); 
     } 
    } 
    request.open("GET", url, true); 
    request.send(); 
} 




<?php 

    include('connection.php'); 
    $l= array(); 

    $result = mysqli_query($con, "SELECT * FROM users"); 
    while ($row = mysqli_fetch_assoc($result)) { 
     $l[] = $row; 
    } 

    /* encode array as a json object */ 
    $json = json_encode($l); 

    /* send the correct content-type header */ 
    header('Content-Type: application/json'); 

    /* send the data */ 
    exit($json); 

?> 
+0

問題已被Ram Raider在上述評論中解決。 –