从数据库查询返回一个数组作为JSON,然后使用jQuery将内容放入列表元素中


Returning an array from DB query as JSON and then putting the contents into list elements with jQuery

我有一个评论系统,我正在研究它的目标是像Instagram系统一样。

目前,我在 PHP 中显示最后 3 个项目,并且还有一个"显示所有按钮"。

我的目标是然后单击该按钮并调用一个函数,然后将所有注释作为数组返回。然后我需要将这个数组作为列表元素进行 .prepend()。

通常,使用 AJAX 调用来获取数据是可以的。但在过去,我只重新调整了一行值。

我正在使用Laravel,所以我要获取的函数将是这样的:

public function fetch() {
  DB:: // SELECT ALL COMMENTS
  $commentsArray = array();
  foreach ($comments as $comment) {
     $commentsArray = (array('commentusername', 'comment'));
  }
  return Response::json(array(
    'success' => true,
    'comments' => $commentsArray,
  200)
  );
}

然后在我的jQuery调用中:

if (data.success) {
  $(".comments_"+id).prepend("<li><b>USERNAME:</b> Comment</li>");
}

该前缀将按照我的意愿进行,但我需要学习如何正确创建数组,然后如何遍历它们并在 jQuery 中创建列表元素。

请注意,PHP函数是写在这里的,未经测试等。

谢谢。

首先,使用 array_map 获取所需格式的数组:

public function fetch() {
    DB:: // SELECT ALL COMMENTS
    $commentsArray = array_map(function($comment){
        return array(
                'username' => $comment->commentusername,
                'comment' => $comment->comment
        );
    }, $comments);
    return Response::json(array(
        'success' => true,
        'comments' => $commentsArray
    ));
}

(我将输出数组的注释用户名更改为用户名。此外,您不需要回复中的200

现在,您的响应如下所示:

{
    success: true,
    comments: [
        {username: 'foo', comment: 'comment of foo'},
        {username: 'foo', comment: 'comment of foo'}
    ]
}

然后在你的 JavaScript 代码中,执行以下操作:

if (data.success) {
    for(var i=0; i<data.comments.length; i++){
        var comment = data.comments[i];
        $(".comments_"+id).prepend("<li><b>"+comment.username+":</b> "+comment.comment+"</li>");
    }
}

另请注意,如果对错误使用 HTTP 状态代码,则可以删除success: true并假定如果响应为 200(ajax 成功回调),则请求已成功发出。

我无法理解你的问题,但我要告诉你,你如何从脚本中获取 json 响应,然后可以解析它,

// script.php
<?php
   $data = array(
        array('User' : 'Tiger', 'Comment' : 'Any comment,, '),
        array('User' : 'John', 'Comment' : 'Tiger is nice guy !!') 
   );  // In reality data will fetch from Db 
   header('Content-Type: application/json');  // must be set, and no space between ...pe and ':'
   echo json_encode($data);   
?>

client_side.js

 $.get('script.php', function(data) {
         for(i = 0; i < data.length; i++){
                $(".comments_"+id).prepend("<li><b>USERNAME :</b> " + data[i].User + " <b> Comment :</b> " + data[i].Comment  + "</li>");  // You should use templete here
         } // __prepending comments
 }, 'json');

谢谢:)

首先,您需要将数组添加到数组中。当你这样做时,你总是只是覆盖你的变量:

$commentsArray[] = (array('commentusername', 'comment'));

在变量名称后添加一个[]

然后在jQuery中:

$.each(data, function(idx, obj) {
    $(".comments_"+id).prepend("<li><b>USERNAME:" + obj.commentusername + ", </b> Comment</li>" + obj.comment);
});

注意:不要忘记在循环中检查并更改id