0

我正在尝试使用以下 ajax 和 PHP 代码将表(映射)的两列从 MySQL 数据库加载到 JavaScript 数组,结果如下:

{"0":"218.5149144","x":"218.5149144","1":"215.5990218","y":"215.5990218"}

<script>
$( document ).ready(function() {
    $("#submit").on("click",function(){
        $.ajax({
                type:"POST",
                url:"map.php",
                success: function (html) {
                    $('#message').html(html);
                }
        });
    });
});
</script>

<?PHP   
   define ( 'DB_HOST', 'localhost' );
   define ( 'DB_USER', 'root' );
   define ( 'DB_PASS', '' );
   define ( 'DB_NAME', 'test' );
   $con = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
   $query = "SELECT x,y FROM app";
   $result = $con->->query($query)->fetch_array();
   echo json_encode($result);
 $con->close();

你能告诉我如何修改我的 PHP 以获得如下结果:

 [
   [ 218.5149144 , 215.5990218 ],
   [ 219.2915206 , 216.8274247 ],
   [ 254.5833588 , 311.9862023 ],
   [ 254.2178971 , 314.9889649 ]
 ];
4

1 回答 1

1
<?php
define ( 'DB_HOST', 'localhost' );
define ( 'DB_USER', 'root' );
define ( 'DB_PASS', '' );
define ( 'DB_NAME', 'test' );
$con = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$query = "SELECT x,y FROM app";
$results = $con->query($query);
$return = array();
if($results) {
while($row = $results->fetch_assoc()) {
    $return[] = array((float)$row['x'],(float)$row['y']);
}
}
echo json_encode($return);
$con->close();
?>
于 2014-05-28T04:16:40.167 回答