-2
  <?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"} 
4

1 回答 1

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);

只需确保您设置了这些,然后再回显任何内容...

于 2013-08-15T23:00:57.583 回答