json适用于静态文件但不适用于动态php

时间:2013-06-25 12:31:17

标签: php json

抓住我的头。我正在尝试将json转换为HTML列表。如果json在静态文件中,一切正常。如果我运行一个脚本,它不会。如果我在静态文件中使用脚本的输出,它就可以工作。

处理json的代码:

<div id="placeholder"></div>
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script>
         $.getJSON('community.php', function(data1) {
               var output="<ul>";
               for (var i in data1.users1) {
                 output+="<li>" + data1.users1[i].Community_post_author + " " + data1.users1[i].Community_post_message + "--" + data1.users1[i].Community_post_time_stamp+"</li>";
               }
               output+="</ul>";
               document.getElementById("placeholder").innerHTML=output;
         });
     </script>

创建json的代码:

$rows = array();
while($r = mysql_fetch_assoc($community_records)) {
  $rows[] = $r;
}

echo json_encode(array('users1' => $rows));

提前感谢您的帮助!


根据评论(谢谢!)这里是脚本输出:

{“users1”:[{“Community_post_time_stamp”:“2013-06-25 06:41:13”,“Community_post_type”:“社区”,“Community_post_status”:“live”,“Community_post_author”:“MikeB” ,“Community_post_message”:“system check”},{“Community_post_time_stamp”:“2013-06-22 08:27:34”,“Community_post_type”:“community”,“Community_post_status”:“live”,“Community_post_author”:“ fish2011“,”Community_post_message“:”每天一个苹果不能让医生离开“},{”Community_post_time_stamp“:”2013-06-22 08:26:40“,”Community_post_type“:”社区“,”Community_post_status“ :“live”,“Community_post_author”:“grumpy”,“Community_post_message”:“另一天另一美元”},{“Community_post_time_stamp”:“2013-06-22 08:26:10”,“Community_post_type”:“社区” ,“Community_post_status”:“live”,“Community_post_author”:“devgirl”,“Community_post_message”:“赞美此计划”},{“Community_post_time_stamp”:“2013-06-22 08:25:51”,“Community_post_type” : “社区”, “Community_post_status”: “活”, “Community_post_author”: “devguy”,“Community_post_me ssage“:”我今天清醒了一年“},{”Community_post_time_stamp“:”2013-06-22 08:25:28“,”Community_post_type“:”社区“,”Community_post_status“:”live“,”Community_post_author “:”raccoongrrll“,”Community_post_message“:”丢失我的手机充电器“},{”Community_post_time_stamp“:”2013-06-22 08:24:49“,”Community_post_type“:”社区“,”Community_post_status“:”直播“,”Community_post_author“:”raccoongrrll“,”Community_post_message“:”诊所有wifi吗?“},{”Community_post_time_stamp“:”2013-06-22 08:23:41“,”Community_post_type“:”社区“ ,“Community_post_status”:“live”,“Community_post_author”:“devguy”,“Community_post_message”:“我女朋友让我发疯”},{“Community_post_time_stamp”:“2013-06-22 08:22:36”,“ Community_post_type“:”community“,”Community_post_status“:”live“,”Community_post_author“:”devgirl“,”Community_post_message“:”今天是我的生日!“}}}

2 个答案:

答案 0 :(得分:0)

我已经在本地测试了您的代码并且只使用了一个示例数据库 - 一切正常。正如有人提到的那样:确保没有其他的回声&#39;与你的JSON数据混合在一起,否则它可能是mysql查询返回的数据..也许它是空的?

答案 1 :(得分:0)

尝试将header('Content-Type: application/json')添加到PHP文件中。