2015-12-21 243 views
1

我在這裏遇到問題!由於我在JSON和JS方面缺乏知識,似乎有些問題。下面是我的一些代碼:將PHP數組轉換爲JavaScript對象

$markersData = array(); 

$x = 0; 
while ($row = @mysqli_fetch_assoc($result)) 
{ 
    $type = $row['type']; 
    $markersData[$type][$x]['name'] = $row['name']; 
    $markersData[$type][$x]['location_latitude'] = $row['location_latitude']; 
    $markersData[$type][$x]['location_longitude'] = $row['location_longitude']; 
    $markersData[$type][$x]['map_image_url'] = ''; 
    $markersData[$type][$x]['name_point'] = $row['name_point']; 
    $markersData[$type][$x]['description_point'] = $row['description_point']; 
    $markersData[$type][$x]['url_point'] = $global['rootURI'] . '/view.php?id=' . $row['id']; 
    $x ++; 
} 

,我檢索行後直接存儲PHP陣列上的SQL數據。現在,使用JSON方法,這裏是我的試用版,但顯然它沒有加載或工作。

var 
    mapObject, 
    markers = [], 
    markersData = JSON.parse('<?php echo json_encode($markersData); ?>'); 

而我要找的轉換PHP數組做同樣的工作,因爲這JS代碼:

var 
    mapObject, 
    markers = [], 
    markersData = { 
      'Shop': [ 
      { 
       name: 'Bondi Beach', 
       location_latitude: 43.119445, 
       location_longitude: 131.881006, 
       map_image_url: 'img/img.png', 
       name_point: 'Vladivostok', 
       description_point: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard', 
       url_point: '02.html' 
      } 
      ], 
      'Cinema': [ 
      { 
       name: 'Bondi Beach', 
       location_latitude: 43.124034, 
       location_longitude: 131.883517, 
       map_image_url: 'img/img.png', 
       name_point: 'Vladivostok', 
       description_point: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard', 
       url_point: '02.html' 
      }, 
      { 
       name: 'Coogee Beach', 
       location_latitude: 43.126117, 
       location_longitude: 131.877423, 
       map_image_url: 'img/img2.png', 
       name_point: 'Matart Group', 
       description_point: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard', 
       url_point: '02.html' 
      } 
      ] 
     }; 

我在做什麼錯在這裏?

編輯:幾個人問我向他們展示輸出。它可在這裏:http://pastebin.com/7Ebz2GzP

+6

嘗試直接'markersData = <?php回聲json_encode($ markersData); ?>;' – Jigar

+0

請顯示'echo json_encode($ markersData)的輸出;' – Steve

+0

打印編碼的json字符串的結果並驗證uisng'http:// jsonlint.com /' – Butterfly

回答

0

您應該使用json_encode將數據發送給JavaScript像

echo json_encode($markersData); 

,然後在JavaScript中,你可以使用JSON.parse,使之成爲JavaScript對象

response = JSON.parse(markersData, function(k,v){ 
        return v; 
       }); 
    console.log(response); 
0

使用json_encode

echo json_encode($markersData); 

在JS解析它:

res = JSON.parse(markersData, function(a,b){ return b;}); 
    alert(res);