通过php将坐标从mysql传递给js

时间:2014-06-23 17:37:08

标签: javascript php mysql

所以,我有一个工作的js脚本,它调用一个执行mysql查询的php脚本。 不好的部分是当我尝试将坐标传递回js脚本时因为它们未格式化。 例: 我想要的数组是{xx.xxxxxxx,yy.yyyyyyy ...} 相反,我得到{xx.xxxxxxxyy.yyyyyyy等等}。 这是php查询代码UPDATED:

<?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代码,当它从查询中获取数据时调用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 code

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);
}

任何帮助?

1 个答案:

答案 0 :(得分: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。你也必须相应地调整数据加法器。

并在评论中说,添加application / json作为您的内容类型