使用ajax添加和删除评论?

时间:2014-03-28 00:22:39

标签: javascript php mysql ajax comments

我使用php创建了一个简单的添加和删除注释系统。夫妻问题。

  1. 在我发表评论并刷新页面后,它会再次发布相同的评论。
  2. 我可以删除评论,但在刷新页面之前不会显示它已被删除。再一次刷新页面,它将加载重复的评论。
  3. 所以我假设我最好的选择是使用ajax路由来执行此操作而不刷新页面。 下面说的是添加和显示评论的基本设置。你会如何为它创建ajax?

    添加评论表单

          <form action="" method="post" enctype="multipart/form-data">
             <div class="field-comment">
                  <label for="name">Enter your comment</label><br>
                   <input type="text" name="comment" size="60">
             </div>
             <input type="submit" value="Post">
          </form>
    

    显示评论

    <div id="show-comments"></div>
    

    删除评论按钮

    <div class="delete_comment">
    <a href="delete_comment.php?id=<?php echo $comment_id; ?>"><p><img src="images/icon_del.gif" alt="delete"></p></a>
    </div>
    

    所以这些是我在网站头部的删除功能。

    <script>
        function deleteClick () {
            deleteComment($(this).data('id'));
        }
    
        function deleteComment(id) {
            $.ajax('delete_comment.php', {
                type: 'POST',
                data: {
                    id: id
                },
                success: function() {
                    //Ajax successful: remove the comment div from your comment area
                    $('.comment-' + id).remove();
                },
                error: function() {
                    //Ajax not successful: show an error
                    alert('An error occured while deleting the comment!');
                }
            });
        }
        $('.delete_comment').click(deleteClick);
    </script>
    

    这是说index.php上的删除div

    <div id="comment-<?php echo $comment_id; ?>" class="comment">
                        This is a comment.
                        <a data-id="<?php echo $comment_id; ?>" href="#" class="delete_comment">
                            <p><img src="images/icon_del.gif" alt="delete"></p>
                        </a>
                    </div>
    

    这是delete_comment.php的删除功能

    $delete     =   $dbh->prepare("DELETE from comments WHERE comment-id = {$comment_id}");
    

3 个答案:

答案 0 :(得分:0)

您可以使用它来显示评论的实时Feed:

setInterval(function showcomments() {
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
csxmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
csxmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
}
csxmlhttp.onreadystatechange=function comments()
{
if (csxmlhttp.readyState==4 && csxmlhttp.status==200)
    {
    document.getElementById('show-comments').innerHTML=csxmlhttp.responseText;
    }
}
csxmlhttp.open('GET','show_comments.php',true);
csxmlhttp.send();
}, 1000);

然后将注释的id发送到php脚本,该脚本将删除数据库中的注释,然后alert()将其删除:

function deletecomment() {
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
dcxmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
dcxmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
}
dcxmlhttp.onreadystatechange=function dcomment()
{
if (dcxmlhttp.readyState==4 && dcxmlhttp.status==200)
    {
    alert('Comment Deleted!')
    }
}
dcxmlhttp.open('GET','delete_comment.php?id=' + comment_id,true);
dcxmlhttp.send();
}

这就是你要找的东西吗?

答案 1 :(得分:0)

您可以使thispage.php更像:

<?php
  /* execute comments query -- echo $comments with the proper HTML formatting
     surrounding each comment */
?>
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
   <head>
     <meta http-equiv='content-type' content='text/html;charset=utf-8' />
     <style type='text/css'>
       @import 'common.css'; @import 'thispage.css';
     </style>
   </head>
<body class='njs'>
  <div class='field-comment'>
    <label for='comment'>Enter your comment</label>
    <input type='text' name='comment' id='comment' maxsize='60' />
    <input type='button' name='pst' id='pst' value='Post' />
  </div>
  <div id='added-comments'>
    <div id='comments'><?php echo $comments;?></div>
  </div>
  <script type='text/javascript' src='common.js'></script>
  <script type='text/javascript' src='post.js'></script>
  <script type='text/javascript' src='thispage.js'></script>
</body>
</html>

现在让我们看看common.js

//<![CDATA[
var doc = document, bod = doc.body, IE = parseFloat(navigator.appVersion.split('MSIE')[1]);
bod.className = 'js';
function gteIE(version, className){
  if(IE >= version)bod.className = className;
}
function E(e){
  return doc.getElementById(e);
}
//]]>

现在你的学习。这是post.js

//<![CDATA[
function post(where, send, success){
  var x = new XMLHttpRequest || new ActiveXObject('Microsoft.XMLHTTP');
  var v = encodeURI(send);
  x.open('POST', where); x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  x.setRequestHeader('Content-length', v.length); x.setRequestHeader('Connection', 'close');
  x.onreadystatechange = function(){
    if(x.readyState === 4 && x.status === 200){
      success(x.responseText);
    }
  }
  x.send(v);
}
//]]>

现在我们需要查看thispage.js

//<![CDATA[
E('pst').onclick = function(){
  var cmt = E('comment').value;
  if(cmt !== ''){
    post('response.php', 'comment='+cmt, function(o){
      var div = doc.createElement('div'), del = doc.createElement('input');
      del.type = 'input'; del.value = 'Delete';
      div.appendChild(doc.createTextNode(o)); div.appendChild(del);
      E('comments').appendChild(div);
    });
  }
  else{
    // a comment was not entered
  }
}
var psts = E('comments').childNodes, cn, ip;
for(var i=0,l=psts.length; i<l; i++){
  (function(i){
    cn = psts[i].childnodes;
    for(var n=0,c=cn.length; n<c; n++){
      (function(n){
        ip = cn[n];
        if(ip.nodeName.match(/^input$/i)){
          ip.onclick = function(){
            post('response.php', 'delete='+ip.previousSibling.nodeValue, function(o){
              if(o){
                bod.removeChild(ip.parentNode);
              }
              else{
                // put error code here
              }
            });
          }
        }
      })(n);
    }
  })(i);
}
//]]>

response.php

怎么样?
<?php
if(isset($_POST['comment'])){
  $cmnt = $_POST['comment'];
  /* run database table column row INSERT based on $cmnt -- echo $cmnt when query
     is executed correctly
  */
}
elseif(isset($_POST['delete'])){
  /* run database table column row DELETE based on the actual comment which you
     can find in $_POST['delete'] -- Once you have executed query echo 1, which
     will go back to JavaScript page `onreadystatechange`
  */   
}
?>

答案 2 :(得分:0)

首先你需要改变一下你的形式:

<form action="#">
    <div class="field-comment">
        <label for="commentText">Enter your comment</label><br>
        <input type="text" name="commentText" id="commentText" size="60">
    </div>
    <input type="submit" value="Post">
</form>

然后,使用jQuery,脚本将类似于:

//Event handler for click on a delete button
function deleteClick () {
    deleteComment($(this).data('id'));
}

function addComment(commment) {
    //Create a new div with id "comment-[id]" containing the comment
    var $commentDiv = $('<div />', {
        id: 'comment-' + comment.id,
        'class': 'comment',
        html: comment.text
    };

    //Create the delete button with the attribute data-id, 
    //which will be used for deleting
    var $deleteLink = $('<a href="#" data-id="' + comment.id + '"/>', {
        'class': 'delete_comment',
        html: '<p><img src="images/icon_del.gif" alt="delete"></p>',
        click: deleteClick //Reference to the event handler we created above
    });

    //Add the delete button to the comment div
    $commentDiv.append($deleteLink);
    //Add the comment div to your comment area
    $('#show-comments').append($commentDiv);
}

function deleteComment(id) {
    $.ajax('delete_comment.php', {
        type: 'POST',
        data: {
            id: id
        },
        success: function() {
            //Ajax successful: remove the comment div from your comment area
            $('#comment-' + id).remove();
        },
        error: function() {
            //Ajax not successful: show an error
            alert('An error occured while deleting the comment!');
        }
    });
}

$(function() {
    $('#comment-form').submit(function(event) {
        //Skip the form from submitting
        event.preventDefault();

        var commentText = $(this).find('#commentText').val();

        //Ensure commentText to not be empty
        if($.trim(commentText).length) {
            $.ajax('add_comment.php', {
                type: 'POST',
                data: {
                    commentText: commentText
                },
                success: function(response) {
                    //Ajax successful: call the addComment function
                    addComment(response);
                },
                error: function() {
                    //Ajax not successful: show an error
                    alert('An error occured while saving the comment!');
                }
            };  
        }          
    });

    //Find all delete buttons and add the event handler we created above.
    //This expects the delete buttons to have a data-id attribute containing 
    //the id of the comment that should be deleted
    $('.delete_comment').click(deleteClick);
});

执行以下操作:

  1. 等到页面加载($(function() {}))并向表单中添加事件处理程序以提交事件
  2. 从提交(event.preventDefault()
  3. 中略过表单
  4. 检查是否输入了评论(if($.trim(commentText).length))并调用ajax函数
  5. 期待您的add_comment.php返回包含两个字段的JSON:idtextid是新添加的评论的ID,text只包含添加的文字
  6. 使用ID&#34; comment- [id]&#34;创建一个新的div。包含评论和删除按钮(我跳过了删除的div,因为我认为它不是必要的)
  7. 向删除按钮添加事件处理程序,该按钮在单击
  8. 时调用deleteComment函数
  9. 执行ajax调用以删除评论,然后删除包含评论的div
  10. 将事件处理程序添加到已存在的删除按钮
  11. 这应该可以胜任,但我还没有测试过。有关ajax功能的更多详细信息,请参阅jQuery documentation。对于这个功能来说,jQuery可能看起来有些开销,但是它使得发送ajax和创建新的DOM元素变得更容易。请告诉我是否需要澄清一些事情。

    修改

    根据评论中的要求,这是包含评论和删除按钮的div的示例:

    <div id="comment-1234" class="comment">
        This is a comment.
        <a data-id="1234" href="#" class="delete_comment">
            <p><img src="images/icon_del.gif" alt="delete"></p>
        </a>
    </div>
    

    点击删除按钮会获取属性data-id(代码中的$(this).data('id'))的值,并使用id作为属性调用函数deleteComment(在这种情况下为1234) )。该函数发送一个ajax请求并删除id为#34; comment- [id]&#34;的div,所以在这个例子中&#34; comment-1234&#34;。