php - 刷新评论区

标签 php javascript jquery json

我编写了一个 JQuery 脚本,当输入评论时,它会转到数据库并将结果拉回并将其显示在页面上。这很好用,但是我需要一个单独的页面,其中只有评论,每 5 秒自动刷新一次结果(而不是在浏览器上单击刷新)。我还想了解 FadeIn 的评论。我尝试使用我在网上找到的资源来做到这一点,但其中大多数似乎不断复制我的内容并刷新。

你能帮忙吗? enter image description here

Comments.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="comments.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Live Comments</title>
</head>
<body>
<div id="leaveComment">
  <h2>Leave a Comment</h2>
  <div class="row">
    <label>Your Name:</label>
    <input type="text">
  </div>
  <div class="row">
    <label>Comment:</label>
    <textarea cols="10" rows="5"></textarea>
  </div>
  <button id="add">Add</button>
</div>
<div id="comments">
  <h2>Live Comments</h2>
</div>
<script type="text/javascript" src="jquery-1.6.1.min.js"></script> 
<script type="text/javascript">
            $(function() {

                //retrieve comments to display on page
                $.getJSON("comments.php?jsoncallback=?", function(data) {

                    //loop through all items in the JSON array
                    for (var x = 0; x < data.length; x++) {

                        //create a container for each comment
                        var div = $("<div>").addClass("row").appendTo("#comments");

                        //add author name and comment to container
                        $("<label>").text(data[x].name).appendTo(div);
                        $("<div>").addClass("comment").text(data[x].comment).appendTo(div);
                    }
                }); 
                //add click handler for button
                $("#add").click(function() {

                    //define ajax config object
                    var ajaxOpts = {
                        type: "post",
                        url: "addComment.php",
                        data: "&author=" + $("#leaveComment").find("input").val() + "&comment=" + $("#leaveComment").find("textarea").val(),
                        success: function(data) {

                            //create a container for the new comment
                            var div = $("<div>").addClass("row").appendTo("#comments"); 

                            //add author name and comment to container
                            $("<label>").text($("#leaveComment").find("input").val()).appendTo(div);
                            $("<div>").addClass("comment").text($("#leaveComment").find("textarea").val()).appendTo(div).hide().fadeIn("slow");

                            //empty inputs
                            $("#leaveComment").find("input").val("");
                            $("#leaveComment").find("textarea").val("");
                        }
                    };

                    $.ajax(ajaxOpts);

                });     
            });     
        </script>
</body>
</html>

Moderator.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="comments.css">
</head>
<body>
<div id="comments">
  <h2>Live Comments</h2>
</div>
<script type="text/javascript" src="jquery-1.6.1.min.js"></script> 
<script type="text/javascript">
            $(function() {

                //retrieve comments to display on page
                $.getJSON("comments.php?jsoncallback=?", function(data) {

                    //loop through all items in the JSON array
                    for (var x = 0; x < data.length; x++) {

                        //create a container for each comment
                        var div = $("<div>").addClass("row").appendTo("#comments");

                        //add author name and comment to container
                        $("<label>").text(data[x].name).appendTo(div);
                        $("<div>").addClass("comment").text(data[x].comment).appendTo(div);
                    }
                }); 
                //add click handler for button
                $("#add").click(function() {

                    //define ajax config object
                    var ajaxOpts = {
                        type: "post",
                        url: "addComment.php",
                        data: "&author=" + $("#leaveComment").find("input").val() + "&comment=" + $("#leaveComment").find("textarea").val(),
                        success: function(data) {

                            //create a container for the new comment
                            var div = $("<div>").addClass("row").appendTo("#comments"); 

                            //add author name and comment to container
                            $("<label>").text($("#leaveComment").find("input").val()).appendTo(div);
                            $("<div>").addClass("comment").text($("#leaveComment").find("textarea").val()).appendTo(div).hide().fadeIn("slow");

                            //empty inputs
                            $("#leaveComment").find("input").val("");
                            $("#leaveComment").find("textarea").val("");
                        }
                    };

                    $.ajax(ajaxOpts);

                });     
            });     
        </script>
</body>
</html>

Comments.php

<?php

    //db connection detils
    $host = "localhost";
  $user = "CommentsDB";
  $password = "password";
  $database = "comments";

    //make connection
  $server = mysql_connect($host, $user, $password);
  $connection = mysql_select_db($database, $server);

    //query the database
  $query = mysql_query("SELECT * FROM comments");

    //loop through and return results
  for ($x = 0, $numrows = mysql_num_rows($query); $x < $numrows; $x++) {
        $row = mysql_fetch_assoc($query);

        $comments[$x] = array("name" => $row["name"], "comment" => $row["comment"]);        
    }

    //echo JSON to page
    $response = $_GET["jsoncallback"] . "(" . json_encode($comments) . ")";
    echo $response;

?>

addComments.php

<?php

  //db connection detils
  $host = "localhost";
  $user = "CommentsDB";
  $password = "password";
  $database = "comments";

  //make connection
  $server = mysql_connect($host, $user, $password);
  $connection = mysql_select_db($database, $server);

  //get POST data
  $name = mysql_real_escape_string($_POST["author"]);
  $comment = mysql_real_escape_string($_POST["comment"]);

  //add new comment to database
  mysql_query("INSERT INTO comments VALUES(' $name ',' $comment ')");

?>

最佳答案

QUOTE: auto refreshes the results every 5 seconds

使用此代码。

function checkForComments() {}

$(document).ready(function () {
  //Wait 5 seconds then call checkForComments();
  setInterval("checkForComments()", 5000);
});

这里的 5000 是以毫秒为单位的时间,相当于 5 秒。

<小时/>

QUOTE: but most of them seem to keep replicating my content as well as refreshing.

从您的问题中不清楚 comments.php 到底输出什么。如果它输出数据库中的所有评论,最好的选择是保留已发布到页面的评论 ID 数组。只需在 JavaScript 中编写一个函数检查该数组中是否存在特定 ID,并如果不存在则附加它强>.

<小时/>

QUOTE: What I would also like is for the comments to FadeIn

关注这个问题 Making my ajax updated div fade in

已更新

用于加载评论的 JavaScript

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
    //stores the comment IDs
    var comments=new Array();
    var count=1 ;
    function checkForComments() {
        $.getJSON("comments.php", addComments);
    }
    function addComments(data) {
        //loop through all items in the JSON array
        for (var x = 0; x < data.length; x++) {
            alert(data[x].id);
            if(jQuery.inArray(data[x].id, comments)==-1){
                comments[count] = data[x].id;
                //create a container for each comment
                var div = $("<div>").addClass("row").appendTo("#comments");
                //add author name and comment to container
                $("<label>").text(data[x].name).appendTo(div);
                $("<div>").addClass("comment").text(data[x].comment).appendTo(div);
                count++;
            }
        }
    }


    $(document).ready(function () {
        checkForComments();
        setInterval("checkForComments()", 5000);
    });
</script>

我的评论.php

<?php
//make connection
$server = mysql_connect($host, $user, $password);
$connection = mysql_select_db($database, $server);

//query the database
$query = mysql_query("SELECT * FROM comments");

//loop through and return results
for ($x = 0, $numrows = mysql_num_rows($query); $x < $numrows; $x++) {
    $row = mysql_fetch_assoc($query);
    //I have added ID here, 
    $comments[$x] = array("id" => $row["id"], "name" => $row["name"], "comment"
        => $row["comment"]);
}

echo json_encode($comments);
?>

评论表的 SQL

CREATE TABLE IF NOT EXISTS `comments` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(64) NOT NULL,
  `comment` text NOT NULL,
  PRIMARY KEY (`id`)
)

关于php - 刷新评论区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6465403/

相关文章:

php - 从 xampp 导入 MySQL 数据

php - 为 PHP echo 计算并显示不同列中的多个 mysql 行值

php将json字符串转换为数组

javascript api简化

javascript - 选择另一个后启用 selectBox

javascript - Jq Bootstrap 多选 - 必须至少选择一个值

javascript - 在 VueJS 中使用计算属性过滤结果时,如何显示数组中的所有文章?

Jquery - 将 ascii 字符转换回 HTML

jquery - ASPXGridview更新事件回调后执行jquery

javascript - 与固定元素和可滚动内容对齐