我目前正在尝试从我正在对连接到 MySql 数据库的 PHP 文件进行的 ajax 调用中检索多行。
我的代码如下所示:
jQuery/HTML
<script>
$(document).ready(function(){
function getComments(){
var boxid = document.location.hash.substring(1); // remove #
$.ajax({ //Make the Ajax Request
type: "POST",
url: "getComments.php", //file name
data: {boxid: boxid},
success: function(server_response){
var data = $.parseJSON(server_response);
var html = '', comment;
for(var i = 0; i < data.length; i++){
comment = data[i];
html += '<div id="' + comment.user_id + '"><span>' + comment.username + '</span><span>' + comment.comment + '</span></div>';
}
$('#ajax_comment').html(html);
}
});
}
});
</script>
<span name="ajax_comment" id="ajax_comment"></span>
PHP (getComments.php)
session_start();
include('config.php');
if (isset($_SESSION['userid']))
$userid = $_SESSION['userid'];
else
$userid = 0;
if (isset($_POST['boxid']))
{
$knownid = $_POST['boxid'];
$query = mysql_query("SELECT u.id, u.USERNAME, c.COMMENT, c.DATE_ADDED, c.ACTIVE, c.id FROM ratemybox.USERS u, ratemybox.COMMENTS c WHERE u.id = c.user_id and c.box_id = $knownid ORDER BY c.DATE_ADDED DESC");
$result = mysql_fetch_array($query);
$results = array();
foreach($result as $row)
{
$user_id = $row['id'];
$username = $row['username'];
$comment = $row['comment'];
$dateAdded = $row['date_added'];
$results[] = array("user_id" => $user_id, "username" => $username, "comment" => $comment, "date_added" => $dateAdded);
}
echo json_encode($results);
}
这没有产生我期望的结果。任何建议都会很棒。
编辑
使用 Firebug 时出现以下错误:
Illegal string offset 'id' in
Illegal string offset 'username'
Illegal string offset 'comment'
Illegal string offset 'date_added'
不确定这是否有帮助?