如何用ajax刷新评论?

问题描述 投票:0回答:2

我想使用ajax来自动更新页面,这样当有新的评论加入时,我就不必刷新页面来查看。在我的代码中,我有一个注释出来的部分,我试图做到这一点。我可以添加新的评论,但当我这样做时,我必须刷新页面才能看到新的评论,我只是想让它在发布时自动出现。

$(document).ready(function() {

     var comments = document.getElementById("allcomments").value; 

     //Get Storage 
                var username = window.localStorage.getItem("username");

        // Call Ajax for existing comments
        $.ajax({
        type: 'GET',
        url: 'URL.php',
        success: function(result) {
            var arr = JSON.parse(result);

            for(var i = 0; i < arr.length; i++) {
                var obj = arr[i];   

                var output = document.getElementById("allcomments");  

                output.innerHTML += '<div class="comment-container"><div class="username">'+obj.username+'</div><div class="comment">'+obj.comment+'</div><div class="date">'+obj.commDate+'</div><div class="like">'+obj.sentiment+'</div></div>';

            }

        }
    });

    return false;
}); 

/*//Refresh comments
 var int=self.setInterval("showComments()",5000);

    function showComments(){
        $.post("comments.php", function ( arr ) {
            $("#allcomments").html( arr );
        });
    } */

HTML

            <h1>Forum</h1>
                <form id="forumPost" method='POST'>
                   <textarea rows="3" col="60" name="comment" placeholder="Create a Post..." id="comment"></textarea>
                   <button><input type='submit' name='submit' value='Post' class="post"></button>
                </form>
                <p id="error" class="errormessage"></p>
                <p id="allcomments" class="postmessage"></p>

                <div class="comment-container">
                    <div class="username"><!--obj.username--></div>
                    <div class="comment"><!--obj.comment--></div>
                    <div class="date"><!--obj.commDate--></div>
                    <div class="like"><!--obj.sentiment--></div>
                </div>

PHP

// Print out existing comment
$query  = "SELECT comments.commDate, comments.ID, comments.username, comments.comment, users.username, comments.sentiment FROM comments LEFT JOIN users ON comments.username = users.username"; 
$result = mysqli_query($db_server, $query);
if (!$result)
    die("Database access failed: " . mysqli_error($db_server));
while ($row = mysqli_fetch_array($result)) {

    $comments[] = $row; 
}

mysqli_free_result($result);

require_once("db_close.php");

echo json_encode($comments);
javascript php html ajax
2个回答
1
投票

试着从这个区块中删除你的代码

$(document).ready(function() {

}

然后改变

<button><input type='submit' name='submit' value='Post' class="post"></button> 

到。

<button><input type='button' id='submit' value='Post' class="post"></button>

现在把你的ajax代码放在这个区块里 And now put your ajax post code in this block:

$("#submit").on("click", function(){

});
© www.soinside.com 2019 - 2024. All rights reserved.