如何在javascript中输出JSON?

时间:2016-11-28 00:49:51

标签: php jquery json

我正在尝试将json对象的结果从php查询打印到javascript中 所以基本上查询结果如下:

{"points":
[{"lat":40.766696929932,"long":-73.990615844727},  
{"lat":40.688514709473,"long":-73.96475982666},
{"lat":40.714504241943,"long":-74.005630493164},  
{"lat":40.704719543457,"long":-74.009262084961},    
{"lat":40.693260192871,"long":-73.968894958496},     
{"lat":40.760955810547,"long":-73.967247009277},

]}

当我尝试获取包含json对象的php变量(使用AJAX)时,我得到:
VM62:1未捕获的SyntaxError:位置1的JSON中出现意外的标记o
我试着谷歌搜索错误与我的代码有什么关系,但我仍然没有得到它 有人可以向我解释如何在javascript中获取json吗?

<?php
$connect = pg_connect("host=127.0.0.1 dbname=datab user=thomas password=iamtom") or die("Could not connect: ");
$result = pg_query($connect,"SELECT geometry FROM table");
if (!$result){
    echo '{"error":"no results"}';
}

$points= array();    
while($row = pg_fetch_array($result)){ 
    $coordinate = json_decode($row['geometry'])->coordinates;
    $p = new stdClass;
    $p->lat = $c_2[0];
    $p->long = $c_1[1]; 
    array_push($points, $p);
}
$output = new stdClass;
$output->points = $points;
echo json_encode($output);
pg_close($connect);
?>

这是我的HTML / JS:

<html>
<head>
<title>Simple Map</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script>
$.ajax({
    type: "GET",
    dataType: "JSON",
    url: "dab.php",
    data: {
        sataVariable: "here is some data send with GET method"
    },
    success: function(data) {
        var j = JSON.parse(data);
        document.writeln(data);   // attempting to take the coordinates and store it in a variable
    },
    error: function(data) {
        console.log(data);
    }
});
</script>
</head>
<body>

</body>
</html>

1 个答案:

答案 0 :(得分:2)

因为您正在向jQuery.ajax()调用dataType: "JSON",因此从AJSON调用中检索到的数据会自动从JSON解析为JavaScript对象(尽管我会切换{ {1}}与"JSON"匹配文档):

  

"json":将响应评估为JSON并返回JavaScript对象。

请勿在成功处理程序中使用"json"再次手动解析响应;只需直接使用JSON.parse()

现在您已将数据放在名为data的JavaScript对象中,您可以与之交互,例如

data