我目前正在尝试从ajax调用中检索多行,这些调用是我连接到MySql数据库的PHP文件。
我的代码如下:
的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'
不确定这是否有帮助?
答案 0 :(得分:1)
在您的选择查询中,您尝试按$ knownid进行过滤,但是,您将变量保留在引号内。尝试更改为:
$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");
答案 1 :(得分:0)
除了已经给出的许多建议(你真的需要在将它添加到查询之前转义$ _POST [“boxid”]之外)很难找到代码的问题而没有一些错误。
尝试在foreach之前添加var_dump($ result)以确保查询返回某些内容或检查浏览器的控制台以查看服务器实际返回的内容。