2015-12-21 241 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);