【问题标题】:Parse JSON array with JavaScript使用 JavaScript 解析 JSON 数组
【发布时间】:2016-06-25 03:16:41
【问题描述】:

我有一个 MySQL 数据库,其中包含一个包含相关数据的纬度和经度表。我正在尝试创建一个 Google Map 并希望使用 JavaScript 解析 JSON 字符串。我看过这里和 YouTube,但我不知道如何解决我做错的事情。

这是我通过 echo 语句得到的 JSON 字符串:

{"cm_mapTABLE":[["1","Angels Rest Photos OR","Angels_Rest_Photos_OR","663","aaj.jpg","2","Angel's Rest","Hike one of the trails in the Gorge with a scenic overlook, stream, and waterfall.","0","blue","4.5","45.5603","-122.171","http:\/\/www.eyehike.com\/pgallery\/index.php?\/category\/6","Angels_Rest_Photos_OR\/aae.thumb.jpg\" ALIGN=left HEIGHT=115 WIDTH=150>","http:\/\/www.eyehike.com\/pgallery\/i.php?\/galleries\/Angels_Rest_Photos_OR\/aaj-th.jpg","","","",""],["2","Ape Canyon Photos WA","Ape_Canyon_Photos_WA","681","PICT0114.jpg","3","Ape Canyon Trail","This trail is popular with hikers and mountain bikers with great views of several mountains.","0","blue","11","46.1653","-122.092","http:\/\/www.eyehike.com\/pgallery\/index.php?\/category\/8","Ape_Canyon_Photos_WA\/PICT0114.thumb.jpg\" ALIGN=left HEIGHT=115 WIDTH=150>","http:\/\/www.eyehike.com\/pgallery\/i.php?\/galleries\/Ape_Canyon_Photos_WA\/PICT0114-th.jpg","","","",""]]} 

这是我的代码:

<!DOCTYPE html>
<head>
<?php
require("phpsqlsearch_dbinfo.php"); // This is the file with your logon info

 //$host="localhost"; //replace with your hostname 
 //$username="root"; //replace with your username 
 //$password=""; //replace with your password 
 //$db_name="$database"; //replace with your database 
 $con=mysqli_connect("$hostname", "$username", "$password", "$database")or die("cannot connect"); 
 //mysqli_select_db("$db_name")or die("cannot select DB");
 $sql = "select * from location_markers WHERE mrk_id < 3"; //replace emp_info with your table name 
 $result = mysqli_query($con, $sql);
 $json_string_data = array();
 if(mysqli_num_rows($result)){
    while($row=mysqli_fetch_row($result)){
        $json_string_data['cm_mapTABLE'][]=$row;
    }
 }
 mysqli_close($con);
 
 // You have to give the json a name to make it accessible by JS, e.g.:
//  echo 'file='.json_encode($json_string_data),';';
 
 // This statement will echo the json output in the displayed web page
 echo json_encode($json_string_data); 
 // please refer to our PHP JSON encode function tutorial for learning json_encode function in detail 
 ?>
 </head>
 <body>
    <script>
    for (i = 0;i < $json_string_data.length;i++){
    var  javascript_string_data=<?php echo json_encode($json_string_data); ?>;
        document.write(cm_mapTABLE.rank[i]);
    }
        </script>
 </body>
 </html>

我正在使用 Firebug,这是错误:

ReferenceError: $json_string_data 未定义

for (i = 0;i

有人可以告诉我在我的 JSON 字符串中引用元素的正确方法吗?我是否需要以某种方式获取 JSON 字符串中的字段名称?

【问题讨论】:

    标签: javascript php mysql json google-maps


    【解决方案1】:

    var javascript_string_data=&lt;?php echo json_encode($json_string_data); ?&gt;; 正在形成一个名为 javascript_string_data 的变量,其中包含一个对象

    您正在尝试访问cm_mapTABLE.rank[i],这实际上被视为window 对象的属性。

    尝试输出

    document.write(javascript_string_data.cm_mapTABLE.rank[i]);
    

    请注意,在依赖先前存储在数据库中的外部数据时,直接分配 JSON 字符串可能会导致安全问题。请改用JSON.parse() 方法。

    您还尝试在 JavaScript 循环中使用 PHP 变量。

    定义你的 JavaScript 变量 before 在循环中使用它:

    var javascript_string_data = JSON.parse('<?echo json_encode($json_string_data); ?>');
    for (i = 0 ; i < json_string_data.length ; i++){
        document.write(javascript_string_data.cm_mapTABLE.rank[i]);
    }
    

    【讨论】:

    • 注意:str_replace 已被编辑删除,因为您需要一个对象而不是字符串,并且代码已更改为 JSON.parse
    • 感谢大家,我在互联网上搜索了格式 json 字符串,并找到了一个可以粘贴我的 JSON 输出并查看其格式的网站,因此我将在以后的帖子中使用它。今晚我将使用 JSON 解析。我让我的旧 Google 地图 V2 基于 Google 电子表格再次运行,所以我有一些喘息的空间。
    • 在我用来获取 mysql 数据的最终代码中。我找到了一个使用 XML 而不是 JSON 的示例。
    【解决方案2】:

    请注意,不推荐使用 mysql,对 mysql 数据库的查询需要 mysqli。 对于 mysqli 查询,您需要包含数据库。您可以在主机的 php 管理页面上找到数据库名称。通过登录 phpmyadmin 并选择“数据库”找到我的,然后查看列表并完全按照数据库列表中显示的方式输入数据库。您可能只有一个数据库。

    <?php
    // The next file has information for $hostname, $username, $password, $database
    require_once("phpsqlsearch_dbinfo.php");
    
    // Start XML file, create parent node
    
    $dom = new DOMDocument("1.0");
    $node = $dom->createElement("markers");
    $parnode = $dom->appendChild($node);
    
    // Opens a connection to a MySQL server
      $connection=new mysqli($hostname, $username, $password, $database);
    if ($connection->connect_error)   die($connection->connect_error);
    
    // Select all the rows in the markers table
    
    $query = "SELECT * FROM markers 
            WHERE 1
            ORDER BY rank, name";
    $result = $connection-> query($query);
    if (!$result)  die($connection->error);
    
    $rows = $result->num_rows;
    
    header("Content-type: text/xml");
    
    // Iterate through the rows, adding XML nodes for each
    for ($j = 0 ; $j < $rows ; ++$j){
        $result->data_seek($j);
        $row = $result->fetch_array(MYSQLI_ASSOC);
    
        // ADD TO XML DOCUMENT NODE
        $node = $dom->createElement("marker");
        $newnode = $parnode->appendChild($node);
        $newnode->setAttribute("mrk_id",$row['mrk_id']);
        $newnode->setAttribute("name",$row['name']);
        $newnode->setAttribute("rank", $row['rank']); 
        $newnode->setAttribute("mileage", $row['mileage']);   
        $newnode->setAttribute("address", $row['address']);
        $newnode->setAttribute("lat", $row['lat']);
        $newnode->setAttribute("lng", $row['lng']);
        $newnode->setAttribute("marker_type", $row['type']);
        $newnode->setAttribute("mcolor", $row['mcolor']);
        $newnode->setAttribute("permalink", $row['permalink']); 
        $newnode->setAttribute("photolink", $row['photolink']); 
        $newnode->setAttribute("routelink", $row['routelink']); 
        $newnode->setAttribute("thumbnail", $row['thumbnail']); 
    }
    
    echo $dom->saveXML();
    
    $result->close();
    $connection->close();
    ?>
    
    Here is the first 5 mysql records output from this code:
    <markers>
    <marker mrk_id="1" name="Bench Lake / Snow Lake"
    rank="1" mileage="2.5" address="" lat="46.7678"
    lng="-121.707" marker_type="" mcolor="blue"
    permalink="https://www.eyehike.com/2016/bench-lake-snow-lake-wa/"
    photolink="http://www.eyehike.com/pgallery/index.php?/category/344"
    routelink="http://www.eyehike.com/pgallery/index.php?/category/345"
    thumbnail="http://www.eyehike.com/pgallery/i.php?/galleries/Snow_Lake_Photos_WA/aai-th.jpg"
    />
    <marker mrk_id="2" name="Benham Falls" rank="1"
    mileage="0.4" address="" lat="43.939"
    lng="-121.414" marker_type="" mcolor="blue"
    permalink="https://www.eyehike.com/2016/benham-falls-or/"
    photolink="http://www.eyehike.com/pgallery/index.php?/category/25"
    routelink="http://www.eyehike.com/pgallery/index.php?/category/26"
    thumbnail="http://www.eyehike.com/pgallery/i.php?/galleries/Benham_Falls_Photos_OR/aaa-th.jpg"
    />
    <marker mrk_id="3" name="Big Creek Falls"
    rank="1" mileage="1.6" address="" lat="46.0931"
    lng="-121.908" marker_type="" mcolor="green"
    permalink="https://www.eyehike.com/2016/big-creek-falls-wa/"
    photolink="http://www.eyehike.com/pgallery/index.php?/category/27"
    routelink="http://www.eyehike.com/pgallery/index.php?/category/28"
    thumbnail="http://www.eyehike.com/pgallery/i.php?/galleries/Big_Creek_Falls_Photos_WA/aac-th.jpg"
    />
    <marker mrk_id="4" name="Burnt Bridge Creek"
    rank="1" mileage="6" address="" lat="45.6361"
    lng="-122.579" marker_type="" mcolor="blue"
    permalink="https://www.eyehike.com/2016/burnt-bridge-creek-trail-wa/"
    photolink="http://www.eyehike.com/pgallery/index.php?/category/35"
    routelink="http://www.eyehike.com/pgallery/index.php?/category/36"
    thumbnail="http://www.eyehike.com/pgallery/i.php?/galleries/Burnt_Bridge_Creek_Photos_WA/aaq-th.jpg"
    />
    <marker mrk_id="5" name="Cape Falcon Trail"
    rank="1" mileage="7" address="" lat="45.7631"
    lng="-123.956" marker_type="" mcolor="blue"
    permalink="https://www.eyehike.com/2016/cape-falcon-or/"
    photolink="http://www.eyehike.com/pgallery/index.php?/category/39"
    routelink="http://www.eyehike.com/pgallery/index.php?/category/40"
    thumbnail="http://www.eyehike.com/pgallery/i.php?/galleries/Cape_Falcon_Photos_OR/aae-th.jpg"
    />
    </markers>
    

    【讨论】:

      猜你喜欢
      • 2016-07-08
      • 1970-01-01
      • 2011-07-02
      • 2012-04-17
      • 2019-07-05
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多