首页 > 解决方案 > 尝试添加回复系统并在我的评论系统上实时获取帖子

问题描述

我整个星期都在努力在我的页面上建立一个有效的评论系统,环顾四周并尝试尽可能多地学习(有一次我很擅长这个,认证和一切,但我似乎已经失去了它)。

我终于让它工作了——它连接到我的数据库没问题,我的数据库接受从表单插入的数据。

但是,我的问题是评论没有实时显示在我的网站上。谁能指出我添加此功能的正确方向?

我的connect.php如下:

<?php
    $connection = mysqli_connect('localhost', '', '', 'london34_db1');

    if(!$connection){
        echo "Error: Unable to connect to MySQL." . PHP_EOL;
        echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
        echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
        exit;
    }

我的commentform.php 如下:

<?php
require('connect.php');

if(isset($_POST) & !empty($_POST)){
    $name = mysqli_real_escape_string($connection, $_POST['name']);
    $email = mysqli_real_escape_string($connection, $_POST['email']);
    $subject = mysqli_real_escape_string($connection, $_POST['subject']);

    echo $isql = "INSERT INTO comments (cid, name, email, subject, status) VALUES ('$id', '$name', '$email', '$subject', 'draft')";
    $ires = mysqli_query($connection, $isql) or die(mysqli_error($connection));
    if($ires){
        $smsg = "Your Comment Submitted Successfully";
    }else{
        $fmsg = "Failed to Submit Your Comment";
    }

    }
?>
<!DOCTYPE html>
<html>
<head>
    <title>Home Page</title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" >

    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <link rel="stylesheet" href="styles.css" >

    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" ></script>
</head>
<body>

<div class="container">

</div>
<div class="container">
    <div class="col-md-8">

        <div class="panel panel-default">
        <div class="panel-heading">Submit Your Comments</div>
          <div class="panel-body">
            <?php if(isset($smsg)){ ?><div class="alert alert-success" role="alert"> <?php echo $smsg; ?> </div><?php } ?>
            <?php if(isset($fmsg)){ ?><div class="alert alert-danger" role="alert"> <?php echo $fmsg; ?> </div><?php } ?>
            <form method="post">
              <div class="form-group">
                <label for="exampleInputEmail1">Name</label>
                <input type="text" name="name" class="form-control" id="exampleInputEmail1" placeholder="Name">
              </div>
              <div class="form-group">
                <label for="exampleInputEmail1">Email address</label>
                <input type="email" name="email" class="form-control" id="exampleInputEmail1" placeholder="Email">
              </div>
              <div class="form-group">
                <label for="exampleInputPassword1">Subject</label>
                <textarea name="subject" class="form-control" rows="3"></textarea>
              </div>
              <button type="submit" class="btn btn-primary">Submit</button>
            </form>
          </div>
        </div>

    </div>
    <div class="col-md-4">

    </div>
</div>
</body>
</html>

有人能指出我正确的方向吗?

谢谢,

标签: phpmysql

解决方案


为了让它“实时”工作,你需要两件事之一。

  1. 发布后刷新您的页面 ( window.location.reload())。你也可以加入一个名字锚。但是,这是过时的,不推荐。

  2. 使用 AJAX 解决您的问题。您有三个选项,XMLHttpRequest, fetch(),或者如果您使用的是 jQuery,则$.ajax().

使用 ajax 现在应该是标准的。因为它允许前端和后端的整体流程更加顺畅。你说让评论工作,所以我会继续这个假设。

假设您有评论表:

<div class="panel-heading">Submit Your Comments</div>
  <!--- code --->
  <form id="comment_form" method="post">
    <!--- more code --->
  </form>
</div>

现在让我们说什么时候发表评论,而不是返回简单的 html 而是返回一个json_encoded对象。

友情提醒,不要$_POST自暴自弃。它只会把事情搞混,让水变脏。我们想要干净的代码。使用处理程序在其他位置创建文件POST

<?
if($_POST) {
  // handle the comment $_POST

  // when complete
  if( success ) {
    print_r(json_encode([
      'success' => true,
      'comment_body' => $_POST['comment']
    ]));
  } else {
    print_r(json_encode([
      'success' => false,
      'message' => 'Something went wrong'
    ]));

    exit;
  }
}

您可以在页面中添加一个简单的fetch()脚本:

<script>
  var form = document.querySelector('#comment_form'),
      // You need a comment section. Since I didn't see one, I will make my own.
      comment_section = document.querySelector('#comment_section');

  form.addEventListener('submit', e => {
    e.preventDefault();

    var data = new FormData(form);

    fetch('path/to/your/script.php', {
      body: data,
      method: form.method,
      credentials: 'same-origin'
    })
    .then(response => response.json()) // this is data from the server, you really want the response from your own page. Thus, the second `then` clause.
    .then(data => {
      // right here is where the magic begins
      // lets assume data to be a json object
      if( data.success == true ) {
        // create a new comment element. This is just an example empty div
        var comment = document.createElement('<div>');
        comment.className = "comment new-comment";
        comment.innerHTML = data.comment_body;
        comment_section.appendChild(comment);
      } else {
        // handle a failed comment
      }
    })
    .catch(err => console.warn(err));
  });
</script>

基本上这里发生的事情是,用户发表评论,你以同样的方式处理它。

但是,在响应中,您收集提交给您的数据,然后appendChild是评论主 div。您可以将其设置为默认情况下有评论。

这是非常基本的,只是一个概念证明。对它做更多的研究。但我希望这能指导你。


推荐阅读