使用JSON刷新数据

时间:2016-10-25 13:03:42

标签: javascript php jquery json ajax

我试图每隔三秒刷新一次页面上的评论。但是,我所拥有的代码并没有刷新注释,它基本上每3秒输出一组相同的注释,但它并没有使用我拥有的类或img标记。它每三秒钟一次又一次地输出。

enter image description here

有没有人知道为什么我使用的方法输出相同的评论集而不是检查是否有新的评论?

AJAX

function commentRetrieve(){

    $.ajax({ 
            url: "ajax-php/comment-retrieve.php",
            type: "get",
            success: function (data) {
            //  console.log(data);
                if (data == "Error!") {
                    alert("Unable to retrieve comment!");
                    alert(data);
                } else {
                    var array = JSON.parse(data);
                    $(array).each(function($value) {
                        if($('#comment-container').find('#comment-' + $value.id).length == 0) {
                            $('#comment-container').prepend($value.html);
                        }
                    });
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                alert(textStatus + " | " + errorThrown);
                console.log("error"); //otherwise error if status code is other than 200.
            }
        });


}
setInterval(commentRetrieve, 3000);

PHP

if ($select_comments_stmt = $con->prepare($select_comments_sql)) {
            //$select_comments_stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $select_comments_stmt->execute();
            $rows = $select_comments_stmt->fetchAll(PDO::FETCH_ASSOC);
            foreach ($rows as $row) {
                $comment_id = $row['id'];
                $comment_user_id = $row['user_id'];
                $comment_username = $row['username'];
                $home_comments = $row['comment'];
                $comment_date = $row['date'];
                $commenter_user_id = $row['user_id'];
                $commenter_img = $row['img'];
                $commenter_img = '<img class="home-comment-profile-pic" src=" '.$commenter_img.'">';
                if ($home_comments === NULL) {
                    echo 'No comments found.';
                } else {
                    $html = "";
                    $html .= '<div class="comment-post-box">';
                    $html .= $commenter_img;
                    $html .= '<div class="comment-post-username">'.$comment_username. '</div>';
                    $html .= '<div>'.$comment_date. '</div>';
                    $html .= '<div class="comment-post-text">'.$home_comments. '</div>';
                    $html .= '</div>';
                    $data = array('id' => $comment_id, 'html' => $html);
                    echo json_encode($data);
                }
            }
        } else {
            echo "Error!";
        }

评论页面,初始SELECT查询在页面加载时加载评论。

<form action="" method="POST" id="comment-form">
            <textarea id="home_comment" name="comment" placeholder="Write a comment..." maxlength="1000" required></textarea><br>
            <input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
            <input id="comment-button" name="submit" type="submit" value="Post">
        </form>
        <div id="comment-container">
<?php
$select_comments_sql = "
    SELECT c. *, p.user_id, p.img
    FROM home_comments AS c
    INNER JOIN (SELECT max(id) as id, user_id 
                FROM profile_img 
                GROUP BY user_id) PI
      on PI.user_id = c.user_id
    INNER JOIN profile_img p
      on PI.user_id = p.user_id
     and PI.id = p.id
    ORDER BY c.id DESC
";

  if ($select_comments_stmt = $con->prepare($select_comments_sql)) {
        $select_comments_stmt->execute();
        if (!$select_comments_stmt->errno) {
            //echo "error";
        }
        $select_comments_stmt->bind_result($comment_id, $comment_user_id, $comment_username, $home_comments, $comment_date, $commenter_user_id, $commenter_img);
    //var_dump($select_comments_stmt);  
        $comment_array = array();
        while ($select_comments_stmt->fetch()) {
            $comment_array[] = $comment_user_id;
            $comment_array[] = $comment_username;
            $comment_array[] = $home_comments;
            $comment_array[] = $comment_date;
            $comment_array[] = $commenter_user_id;
            $comment_array[] = $commenter_img;
            $commenter_img = '<img class="home-comment-profile-pic" src=" '.$commenter_img.'">';
            if ($home_comments === NULL) {
                echo 'No comments found.';
            } else {
                echo '<div class="comment-post-box">';
                echo $commenter_img;
                echo '<div class="comment-post-username">'.$comment_username. '</div>';
                echo '<div>'.$comment_date. '</div>';
                echo '<div class="comment-post-text">'.$home_comments. '</div>';
                echo '</div>';
            }
        }
  }
?>
        </div>

1 个答案:

答案 0 :(得分:0)

您需要在PHP代码中更改以下内容:

echo '<div class="comment-post-box">'; 

以下内容:

echo '<div class="comment-post-box" id="comment-'. $comment_id .'">';

还要在ajax中更改以下内容:

if($('#comment-container').find('#comment-' + $value.id).length == 0) {

对此:

if($('#comment-' + $value.id).length == 0) {

由于ID只能在页面上使用一次,因此我们不关心它的设置位置。

更新1

您的json代码无效,因此我们需要更改您的PHP代码:

所以改变这个:

foreach ($rows as $row) {
            $comment_id = $row['id'];
            $comment_user_id = $row['user_id'];
            $comment_username = $row['username'];
            $home_comments = $row['comment'];
            $comment_date = $row['date'];
            $commenter_user_id = $row['user_id'];
            $commenter_img = $row['img'];
            $commenter_img = '<img class="home-comment-profile-pic" src=" '.$commenter_img.'">';
            if ($home_comments === NULL) {
                echo 'No comments found.';
            } else {
                $html = "";
                $html .= '<div class="comment-post-box">';
                $html .= $commenter_img;
                $html .= '<div class="comment-post-username">'.$comment_username. '</div>';
                $html .= '<div>'.$comment_date. '</div>';
                $html .= '<div class="comment-post-text">'.$home_comments. '</div>';
                $html .= '</div>';
                $data = array('id' => $comment_id, 'html' => $html);
                echo json_encode($data);
            }
        }

对此:

foreach ($rows as $row) {
            $comment_id = $row['id'];
            $comment_user_id = $row['user_id'];
            $comment_username = $row['username'];
            $home_comments = $row['comment'];
            $comment_date = $row['date'];
            $commenter_user_id = $row['user_id'];
            $commenter_img = $row['img'];
            $commenter_img = '<img class="home-comment-profile-pic" src=" '.$commenter_img.'">';
            if ($home_comments === NULL) {
                echo 'No comments found.';
            } else {
                $html = "";
                $html .= '<div class="comment-post-box">';
                $html .= $commenter_img;
                $html .= '<div class="comment-post-username">'.$comment_username. '</div>';
                $html .= '<div>'.$comment_date. '</div>';
                $html .= '<div class="comment-post-text">'.$home_comments. '</div>';
                $html .= '</div>';
                $data[] = array('id' => $comment_id, 'html' => $html);
            }
        }
                echo json_encode($data);

所以我们首先制作一个包含所有注释的数组,这样输出就是对客户端的正确json响应。

更新2:

我已经改变了你的每一个功能:

$(array).each(function(key, value) {
                        if($('#comment-' + value.id).length == 0) {
                            $('#comment-container').prepend(value.html);
                        }
                    });

注意函数中的key,value

之后它正常工作,我注意到你必须改变你的评论 - retrieve.php,因为评论附加了多次。你在这里创建你的评论div,但没有id。所以也要在此文件中将注释框更改为echo '<div class="comment-post-box" id="comment-'. $comment_id .'">';然后它应该正常工作。

您可以通过在数据库中插入新记录来测试它,或者使用浏览器中的Web开发人员工具或像firebug这样的插件在浏览器中删除评论。