doudong2149 2018-07-25 13:11
浏览 59
已采纳

从关联数组打印JavaScript对象

What if I want to console.log only one 1(ANY) javaScript object. Currenly it displays all 1000. Please Look at Php and JS files:

Server.php

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$data = array("coordinates" => array());

$sql = "SELECT Lng, Lat, URL FROM results LIMIT 1000";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $data["coordinates"][] = $row;
    }
}
echo json_encode($data);

Index.js

{
$.ajax({
  dataType: "json",
  url: 'server.php',
  //data: [],
  data: {param: ""},
  success: function(data)
  {
    //JSON.parse(data);  
    console.log(data);
  addMarkers(data,map);
  }
});

}

  • 写回答

3条回答 默认 最新

  • dqj5046 2018-07-25 13:41
    关注

    It helps to understand the json data structure you are outputting, and how you access certain elements from an object made by that json. In your case, you end up with a single object named data (as defined by the .ajax success callback). That object then contains just one keyname with an array of objects. The keyname is coordinates. Inside each array value, is an object from your database row return.

    If you simply wish to show one object from your array of objects, this is all you need:

    console.log( data.coordinates[0] );
    

    That would show the first object in the array (arrays start with [0]).

    console.log( data.coordinates[999] );
    

    That would show the last object in the array of 1000.

    console.log( data.coordinates[ data.coordinates.length-1 ] );
    

    That would show the last object in an array of a variable size, using itself as the determiner.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题