我试图遍历一个MySQL对象,并在另一个页面上使用ajax调用来追加数据,但是我无法获取php将有效的JSON返回给回调。
这显然不起作用…
<?php $db_host = "localhost"; $db_user = "blah"; $db_pass = "blah"; $db_name = "chat"; $mysqli = new MySQLi($db_host, $db_user, $db_pass, $db_name); $myQuery = "SELECT * FROM users"; $result = $mysqli->query($myQuery) or die($mysqli->error); $row = $result->fetch_assoc(); echo json_encode($row); ?>
还是这个…
<?php $db_host = "localhost"; $db_user = "blah"; $db_pass = "blah"; $db_name = "chat"; $mysqli = new MySQLi($db_host, $db_user, $db_pass, $db_name); $myQuery = "SELECT * FROM users"; $result = $mysqli->query($myQuery) or die($mysqli->error); while ( $row = $result->fetch_assoc() ){ echo json_encode($row) . ", "; } ?>
$data = array(); while ( $row = $result->fetch_assoc() ){ $data[] = json_encode($row); } echo json_encode( $data );
这应该做。另外,您可以使用http://jsonlint.com/查看JSON输出有什么问题。
更新: 使用fetch_all()可能也是一个好主意
fetch_all()
$data = $result->fetch_all( MYSQLI_ASSOC ); echo json_encode( $data );