为什么我没有得到JSON响应?

时间:2013-08-15 22:53:29

标签: php jquery json

  <?php
  include ('config.php');
  $stringData = $_POST['dataString']; 
  $sql=mysql_query("SELECT * FROM comments WHERE post_id_fk='$stringData'");

  while($row=mysql_fetch_array($sql)) {
      $user=$row['user_id'];
      $time=$row['time'];
      $comment=$row['comment_content'];
      $respond=array(
          'user'=>$user,
          'time'=>$time,
          'comment'=>$comment
      );
      echo   json_encode ($respond);
  }
  ?>

我有这个脚本,无法弄清楚,这里有什么不起作用以及为什么响应不是JSON?

在Firebug中显示响应:

{"user":"890","time":"2013-08-15 20:34:02","comment":"What's up?"}
{"user":"878","time":"2013-08-15 23:35:45","comment":"opa"} 

1 个答案:

答案 0 :(得分:1)

您可能希望在编码之前将json数据合并到单个对象/数组中:

$output = array();

while($row=mysql_fetch_array($sql)) {
      $user=$row['user_id'];
      $time=$row['time'];
      $comment=$row['comment_content'];
      $respond=array(
          'user'=>$user,
          'time'=>$time,
          'comment'=>$comment
      );
      $output[] =  json_encode ($respond);
}

echo json_encode($output);
如果检测到错误的内容类型,

添加标题可能会有所帮助:

header('Content-Type: application/json');
echo json_encode($output);

请确保在回复任何内容之前设置这些内容......