【问题标题】:How to get json data in javascript如何在javascript中获取json数据
【发布时间】:2015-01-10 10:46:38
【问题描述】:

我在 php 中从数据库中获取值,并将检索到的值编码为 json 数据格式。

php代码:

<?php
require_once('config.php');
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT * FROM theater';
mysql_select_db($dbname);
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_assoc($retval))
{
echo json_encode($row) "\r\n"; 
}
mysql_close($conn);
?>

输出:

{"id":"11","region":"Central","cord_latitude":"12.9237","cord_longitude":"77.5535"}

现在我只需要从 json 数据中获取一些值到 javascript。 我只需要javascript中的cord_latitude和cord_longitude值 如何在 javascript 中获取这些值?

【问题讨论】:

标签: javascript php json


【解决方案1】:

你可以使用JSON.parse(),例如

<script type="text/javascript">
    var json_data = '{"id":"11","region":"Central","cord_latitude":"12.9237","cord_longitude":"77.5535"}';
    var parsed_data = JSON.parse(json_data);

    console.log('long: ' + parsed_data.cord_longitude)
    console.log('lat: ' + parsed_data.cord_latitude)
</script>

【讨论】:

  • 您可能想稍微切换一下代码,在经度之后记录纬度,反之亦然
【解决方案2】:

在 javascript 中解析您的 json 编码字符串:

var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );

【讨论】:

    【解决方案3】:

    变化:

    echo json_encode($row) "\r\n"; 
    

    收件人:

    echo json_encode(array("cord_latitude" => $row["cord_latitude"], "cord_longitude" => $row["cord_longitude"]));
    

    然后使用JSON.parse();:

    json = 'YOUR JSON STRING'
    theater = JSON.parse(json);
    
    console.log('Longitude: ' + theater.cord_longitude)
    console.log('Latitude: ' + theater.cord_latitude)
    

    这样,只有这 2 个字段会越界,从而减少流量,从而加快加载速度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 2018-05-09
      • 2011-12-27
      • 2019-09-17
      相关资源
      最近更新 更多