我有这个ajax
$.ajax({
type: "GET",
url: '../connect.php',
data: "OrB=" + ajaxsend+"&&IOr="+i,
success: function(data)
{
var x = $.parseJSON(data);
var el='<div class="CommentsAw Comment_Hs">\
<img src="../users/'+x[0]+'">\
<span>'+x[1]+'</span>\
<span class="s2">'+x[2]+'</span>\
</div>'
$(".F_W_comments").html().remove();
$(".F_W_comments").html(el);
}
});
和php
if (isset($_GET['OrB'])) {
$OB=$_GET['OrB'];
$I=$_GET['IOr'];
if ($OB=='OO') {
$OB='`Date` ASC';
}else if ($OB=='No') {
$OB='`Date` DESC';
}
$query=$con->query("SELECT id,comment FROM uploads WHERE Rand='$I'");
$row=$query->fetch_row();
$Commentsq=$con->query("SELECT * FROM (SELECT * FROM comments WHERE Post_id='$row[0]' ORDER BY $OB LIMIT 4) AS sub ORDER BY `DATE` ASC") or die($con->error);
while ($CommentRow=$Commentsq->fetch_row()) {
$CommenterPp=$con->query("SELECT Profile_pic FROM user_opt WHERE Username='$CommentRow[3]'");
$CommenterPicture=$CommenterPp->fetch_row();
$CommenterPp=$con->query("SELECT Username FROM users WHERE Id='$CommentRow[3]'");
$CommenterName=$CommenterPp->fetch_row();
echo json_encode(array($CommenterPicture,$CommenterName,$CommentRow));
}
}
但它在控制台中给我一个错误,就像这个
VM654:2 Uncaught SyntaxError: Unexpected token [ in JSON at position 107
[["5734919677561.jpg"],["Murad"],["1842","3","21","1","2016-05-08 21:56:52"]]
[["5734919677561.jpg"],["Murad"],["1843","GOodm","21","1","2016-05-08 21:56:54"]]
[["5734919677561.jpg"],["Murad"],["1845","re","21","1","2016-05-08 21:56:54"]]
[["5734919677561.jpg"],["Murad"],["1844","re","21","1","2016-05-08 21:56:54"]]
我想要的是connect.php从数据库中获取数据然后将其传递给ajax。 但结果是没有什么可能因为我的代码中存在一些错误
答案 0 :(得分:1)
回显几个json编码的字符串并不意味着有效 json。
您需要做的是json_encode
您的数据,echo
一次。
$commenters = array(); // result array
while ($CommentRow=$Commentsq->fetch_row()) {
$CommenterPp=$con->query("SELECT Profile_pic FROM user_opt WHERE Username='$CommentRow[3]'");
$CommenterPicture=$CommenterPp->fetch_row();
$CommenterPp=$con->query("SELECT Username FROM users WHERE Id='$CommentRow[3]'");
$CommenterName=$CommenterPp->fetch_row();
$commenters[] = array($CommenterPicture,$CommenterName,$CommentRow);
}
// while loop over
echo json_encode($commenters);
在你的js中你应该迭代一个对象数组,而不是一个简单的对象,例如:
success: function(data) {
var x = $.parseJSON(data);
for (var k in x) {
console.log(x[k]);
}
}
答案 1 :(得分:0)
暂时删除数组中的数据,生成的JSON结构如下:
[][][][]
那是无效的JSON。解析器需要一个对象或数组,而不是像这样连接在一起的几个数组。
不是在循环中输出响应,而是在循环之后构建总响应并将其输出一次。基本上在PHP中的while
循环之前创建一个空数组,然后将元素推送到循环内的数组上,然后在循环之后回显JSON编码的数组。
我的PHP非常生疏,但在PHP-ish伪代码中它的结构如下:
$result = array();
while ($CommentRow=$Commentsq->fetch_row()) {
// other code...
$result[] = array($CommenterPicture,$CommenterName,$CommentRow);
}
echo json_encode($result);