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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器