2014-06-23 17 views
-1

所以,我有一個工作的js腳本,它調用執行mysql查詢的php腳本。 不好的部分是當我嘗試將座標傳回給js腳本時,因爲它們沒有格式化。 例如: 我想要的數組是{xx.xxxxxxx,yy.yyyyyyy ...} 而是我獲得{xx.xxxxxxxyy.yyyyyyy等等}。 這裏是更新了PHP的查詢代碼:從mysql傳遞座標到js通過php

<?php 
include('config.php'); //richiama lo script per la connessione al database 

$org_name=$_POST['valor']; //riceve il nome dell'organizzazione terroristica desiderata 

$return = array(); 
$query=mysql_query("SELECT longitude, latitude FROM gtdb WHERE `gname` LIKE '$org_name%' and longitude!=''"); //esegue una query al database 
while($row=mysql_fetch_assoc($query)&&$row2=mysql_fetch_assoc($query)){ 
    $return[] = array($row['longitude'], $row2['latitude']); 
} 
header('Content-type: application/json'); 
echo json_encode($return); 
?> 

這裏是javascript代碼觸發查詢,當它從查詢回來的DATAS調用的dataadder功能(見的JS代碼下一節):

var Datas = [new google.maps.LatLng(32.7603282, 46.343451)]; 
$(document).ready(function() { 
$('#gnome').change(function() { 
    var inpval=$(this).val(); 
    $.ajax({ 
     url: 'php/query.php', 
     type: 'post', 
     data: {valor : inpval}, 
     success: function(data) { 
      while(Datas.length > 0) { 
       Datas.pop(); 
      } 
      alert(data); 
      Datas = dataadder(data); 
      initialize(); //reinitialize gmap with the new datas 
          alert(Datas); 
     } 
    }); 
}); 
}); 

dataadder代碼

function dataadder(array){ 
var arr2 = []; 
var i=0; 
var j=1; 
while(j<=array.length){ 
    arr2.push("new google.maps.LatLng("+array[i]+")"); 
    i+=2; 
    j+=2; 
} 
alert(arr2); 
return(arr2); 
} 

任何幫助嗎?

+3

**不要自己設置json的格式。使用內置方法生成一個數組並將其轉換爲json。 –

+0

另外''content-type:application/json'在你的腳本的輸出中可能是需要的 – vogomatix

回答

0

你或許應該json_encode,像這樣的東西嘗試:

$query=mysql_query("SELECT longitude, latitude FROM gtdb WHERE `gname` LIKE '$org_name%' and longitude!=''"); //esegue una query al database 
$return = array(); 
while($row=mysql_fetch_assoc($query)){ 
    $return[] = array($row['longitude'], $row['latitude']); 
    //or $return[] = ''. $row['longitude'] . '.' . $row['latitude']; 
    //if you want one 'xxx.yyy' string per row of the output 
} 
echo json_encode($return); 

這將輸出類似[['xxx','yyyy'], ['xxx','yyyy']]。您需要使用$.getJSON(...)而不是$ .ajax()來調用該php。你也必須相應地調整數據添加器。

並且如評論中所述,添加應用程序/ json作爲您的內容類型

+0

試過並且所有的經度都變成「null」O.o 以及如何添加內容類型? – Vinz29

+0

header('Content-type:application/json'); – Boris

+0

對不起,我讓你的$ spartaco。請嘗試使用我的編輯 – Boris