【问题标题】:Refresh comments section [closed]刷新评论部分[关闭]
【发布时间】:2011-06-24 08:44:16
【问题描述】:

我已经编写了一个 JQuery 脚本,当输入评论时,它会进入数据库并将结果拉回并显示在页面上。这很好用,但是我需要一个仅打开 cmets 的单独页面,它每 5 秒自动刷新一次结果(而不是单击浏览器上的刷新)。我还想要让 cmets 淡入淡出。我已经尝试使用我在网上找到的资源来做到这一点,但它们中的大多数似乎都在不断复制我的内容并且令人耳目一新。

你能帮忙吗?

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 ')");

?>

【问题讨论】:

  • 到目前为止你尝试过什么?你期待什么?什么没有按您的预期工作?
  • 你想在 facebook 上找到类似 cmets 的东西吗?
  • 我尝试了多种不同的方法来刷新,例如: var refreshId = setInterval(function() { $('#comment').load('moderator.html').fadeIn( "慢"); }, 5000);
  • 你为什么关闭我的问题!?

标签: php javascript jquery json


【解决方案1】:

QUOTE:每 5 秒自动刷新一次结果

使用此代码。

function checkForComments() {}

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

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


QUOTE:但他们中的大多数似乎在不断复制我的内容并且令人耳目一新。

从您的问题中不清楚 cmets.php 究竟输出了什么。如果它输出数据库中的所有 cmets,最好的选择是保留 已发布到页面的 cmets 的 ids 数组。只需在 JavaScript 中编写一个 函数,它会检查该数组中是否存在特定 id,如果不存在则追加它强>。


QUOTE:我还想要让cmets淡入

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

更新

JavaScript 加载 cmets

<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>

我的 cmets.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);
?>

用于 cmets 表的 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`)
)

【讨论】:

  • 我会将 cmets.php 添加到我上面的问题中。如果您可以帮助编写代码,我将非常感激,因为我无法真正编写这些东西,我只是将代码混合在一起;)
  • 好的。当 cmets 页面加载时,它是否显示任何 cmets?或者是页面加载后使用js添加到页面的cmets。
  • 是的,应该有一列 'id' 类型为 INT 并设置为 autoincrement 我还添加了SQL 到我上面的帖子。
  • 好的。截断意味着删除表中的所有数据。 SQL 语法是 TRUNCATE TABLE table_name;
  • 对于您遇到的问题..将 INSERT SQL 查询更新为..INSERT INTO comments (name, comment ) VALUES(' $name ',' $comment ')
【解决方案2】:

您有两种选择:添加append()ing 新内容后,删除旧内容。

或者,设置一个“占位符”元素,并在其上使用 .html() - 这样您就可以替换旧内容,而无需添加更多内容。

【讨论】:

  • 我不想删除旧的 cmets,我只需要在版主页面上自动刷新,这样他们“版主”就不需要不断重新加载浏览器来查看新的 cmets正在添加到 cmets.html 页面
  • 我不是说要删除旧的cmets,我是说要删除旧的内容。然后用新内容(包括所有 cmets)替换它。
猜你喜欢
  • 1970-01-01
  • 2013-10-20
  • 2012-04-30
  • 1970-01-01
  • 2020-01-14
  • 2014-08-27
  • 2020-12-27
  • 2014-03-18
  • 2017-07-31
相关资源
最近更新 更多