2016-06-25 10 views
-2

관련 데이터가있는 위도와 경도 테이블이있는 MySQL 데이터베이스가 있습니다. Google Map을 만들고 JavaScript를 사용하여 JSON 문자열을 구문 분석하려고합니다. 나는 여기와 YouTube에서 보았고, 내가 잘못하고있는 것을 해결하는 방법을 모른다. 여기 JavaScript로 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> 

오류된다

다음

내가 내 에코 문을 얻을 내 JSON 문자열입니다

ReferenceError: $json_string_data is not defined

for (i = 0;i < $json_string_data.length;i++){

내 JSON 문자열의 요소를 참조하는 적절한 방법을 알려주시겠습니까? 어떻게 든 JSON 문자열에서 필드 이름을 가져와야합니까?

답변

1

var javascript_string_data=<?php echo json_encode($json_string_data); ?>;오브젝트을 포함하는 변수 javascript_string_data을 형성합니다.

실제로 window 개체의 속성으로 간주되는 cm_mapTABLE.rank[i]에 액세스하려고합니다. 출력

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

시도는 이전에 데이터베이스에 저장된 외부 데이터에 의존 할 때 직접 JSON 문자열을 할당하는 보안 문제가 발생할 수 있음을 유의하십시오. 대신 JSON.parse() 방법을 사용하십시오.

자바 스크립트 루프에서 PHP 변수를 사용하려고합니다.

루프에서 사용하기 전에 자바 스크립트 변수 를 정의

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]); 
} 
+0

주의 :'str_replace'는 문자열이 아닌 객체가 필요하고'JSON.parse'로 변경되었으므로 편집으로 제거되었습니다. –

+0

덕분에 인터넷에서 format json string을 검색하여 JSON 출력을 붙여 넣을 수있는 사이트를 찾고 포맷을 확인하여 향후 게시물에 사용할 것입니다. 오늘 밤 JSON 구문을 사용하겠습니다. Google 스프레드 시트를 기반으로 이전 Google지도 V2가 다시 작동하므로 숨쉴 공간이 생겼습니다. – Steve

+0

마지막 코드에서 mysql 데이터를 가져 오는 중 사용하고 있습니다. JSON 대신 XML을 사용하는 예제를 발견했습니다. – Steve

0

참고 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>