PHP json_encode与JAVASCRIPT JSON.parse

时间:2014-08-23 09:24:13

标签: javascript php json

如果我在PHP中创建一个像这样的json:

          if ( ($result = mysqli_query($link, $sql))  && (mysqli_affected_rows($link)!==0) )  {
                 $entries = array();
                 while ($row = mysqli_fetch_assoc($result)) {
                        $entries[] = $row;
          }
          $data = json_encode($entries);
          echo($data);

我会得到这个结果:

[   
    {"id":"100043","title":"Mini for Sale","session":"1407456000","totalViews":"0"},
    {"id":"100000","title":"test","session":"1408366541","totalViews":"4"},
    {"id":"100001","title":"Le Cappa","session":"1408377143","totalViews":"0"},
    {"id":"100002","title":"Le Cappa","session":"1408378069","totalViews":"0"},
    {"id":"100003","title":"test","session":"1408378833","totalViews":"0"}
]

如果我使用JavaScript执行此操作:console.log(" jsondata:",JSON.parse(data));

(其中数据是上面的json:data = [{" id ...)

我会得到这个结果:

jsondata: [
 Object { id="100043", title="Mini for Sale", session="1407456000", mehr...},
 Object { id="100000", title="test", session="1408366541", mehr...},
 Object { id="100001", title="Le Cappa", session="1408377143", mehr...},
 Object { id="100002", title="Le Cappa", session="1408378069", mehr...},
 Object { id="100003", title="test", session="1408378833", mehr...}]

我的问题:为什么这会有所不同?我如何使用javascript等对象获取PHP json?

更多信息:我试图用dynatable插件实现一个表。它只有在我使用JSON.parse再次传递PHP发送的数据时才有效。这对我来说意味着PHP-json是错误的。

 $.ajax({
  url: 'http://huntinggrounds.de/stats/test.php',
  success: function(data){  console.log("data: ",data);     console.log("jsondata: ", JSON.parse(data));
    $('#my-final-table').dynatable({
      dataset: {
        records: JSON.parse(data)
      }
    });
  }
});

以下是从控制台复制的展位结果。

data: [{"id":"100043","title":"Mini for Sale","session":"1407456000","totalViews":"0"},{"id":"100000","title":"test","session":"1408366541","totalViews":"4"},{"id":"100001","title":"Le Cappa | Franco Gravante","session":"1408377143","totalViews":"0"},{"id":"100002","title":"Le Cappa | Franco Gravante","session":"1408378069","totalViews":"0"},{"id":"100003","title":"test","session":"1408378833","totalViews":"0"}]

jsondata: [Object { id="100043", title="Mini for Sale", session="1407456000", mehr...}, Object { id="100000", title="test", session="1408366541", mehr...}, Object { id="100001", title="Le Cappa | Franco Gravante", session="1408377143", mehr...}, Object { id="100002", title="Le Cappa | Franco Gravante", session="1408378069", mehr...}, Object { id="100003", title="test", session="1408378833", mehr...}]

1 个答案:

答案 0 :(得分:2)

您在控制台中看到的是内存中实际Javascript对象的交互式调试表示。 不是JSON。您的PHP输出已经是该Javascript对象的完美JSON表示。