页面正在刷新,无法进行查询-ajax、php

46scxncf  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(437)
function add_comment(ele) {
  event.preventDefault();
  var username = "<?php echo $current_user; ?>";
  var user_id = "<?php echo $current_user_id; ?>";
  var post_id = $(ele).data('id');
  var comments = $(ele).parent(".comment-section").find(".comment").val();
  alert(comments);
  if (username == "") {
    alert("Please Log in to Star the Post");
    window.location = "http://tobbyandscooby.com/log.php";
    return;
  }
  $.ajax({
    type: 'POST',
    url: 'add_comment.php',
    data: {
      postid: post_id,
      uname: username,
      uid: user_id,
      comment: comments
    },
    success: function(response) {
      //alert("Successfully Comment is Added! ");
    }
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="comment-section">
  <textarea id="<?php echo $post_id; ?>" class="comment" value="" data-id="<?php echo $post_id; ?>"></textarea>
  <button id="btn" class="btn-default" data-id="<?php echo $post_id; ?>" onclick="add_comment(this);">Comment</button>
  <div class="comment-show"></div>
</div>

<?php 
include("connect.php");
$username = $_POST['uname'];
$post_id = $_POST['postid'];
$user_id = $_POST['uid'];
$comments = $_POST['comment'];
$sql = "INSERT INTO comments (user_id,username,post_id,comment) VALUES ($user_id,'$username',$post_id,'$comment')";
$result = $db->query($sql);
?>


我正在尝试用ajax制作一个评论系统。我用ajax做过类似的事情,比如favorite,down-vote,upvote。但是现在有了上面的代码,我无法将数据输入到数据库中,而且单击comment按钮页面会刷新,即使我使用了*preventdefault();
我知道我犯了一些错误,但无法调试它。另外,请建议我如何添加到div.comment显示使用ajax的成功输入的评论。

注意:我可以得到警报(评论);默认时工作();函数被删除!我已经添加了xhr对其他工作正常的元素的请求

nszi6y05

nszi6y051#

问题在于 preventDefault() .
你现在通过了 this 用那个函数调用 onClick .
要解决此问题,请通过添加 <button type="submit" .. 然后传球 event 使用函数调用: ...onClick="add_comment(event);" ```
// complete line:
Comment

但现在需要重写函数的各个部分,因为 `ele` 现在是事件,不再是元素:每 `$(ele)` 至 `$('#id')` 显然,在函数的开头,传入事件的变量名需要匹配:

function add_comment(e) { // whatever you wanna name it, e has to be the same
e.preventDefault(); // as this e

另一个解决方案是保持按钮只是一个普通的按钮,删除onclick,然后添加 `onSubmit="add_comment(event);"` 给你的 `<form..>` 

相关问题