我正在制作一个类似项目的时间表,允许对帖子发表评论。但是我无法插入数据。评论按预期显示。表单值似乎没有传递到 save_comments.php 页面。
下面是代码
配置文件
<?php
$con=new PDO("mysql:host=localhost;dbname=posts&comments","root","");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
索引.php
<?php
include 'config.php';
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<?php
$sql=$con->prepare("SELECT * FROM posts");
$sql->execute();
$results=$sql->fetchAll(PDO::FETCH_ASSOC);
echo "<hr>";
foreach($results as $post){
echo "<h2>".$post['post_title']."</h2><br>";
echo $post['post_content']."<br>";
?>
<br><b>Comments</b>
<form id=comment_form_<?php echo $post['post_id']; ?> action="">
<input type=hidden name=pid value=<?php echo $post['post_id']; ?> >
<p><input type=text name=cbody id="comment_body_<?php echo $post['post_id']; ?>" placeholder="Write comment" ></p>
<p><input type=text name= cauth id="comment_author_<?php echo $post['post_id']; ?>" placeholder="Your Name" ></p>
<p><button class="submit_comment" post_id="<?php echo $post['post_id']; ?>" >Submit</button> </p>
</form>
<p><button class="show_comments" post_id="<?php echo $post['post_id']; ?>">Show comments</button></p>
<div id="comments_<?php echo $post['post_id']; ?>">
</div>
<?php
echo "<hr>";
}
?>
<script>
$(document).ready(function() {
$(".show_comments").click(function() {
var post_id=$(this).attr('post_id');
$("#comments_"+post_id).load("comments.php", {
post_id:post_id
});
});
$(".submit_comment").on("click",function() {
var post_id=$(this).attr('post_id');
$.ajax({
data:$('#comment_form_'+post_id).serialize(),
url:'save_comments.php',
async : true,
success: function(){
$("#comments_"+post_id).load("comments.php", {
post_id:post_id
});
}
})
});
});
</script>
评论.php
<?php
include 'config.php';
$post_id=$_POST['post_id'];
$pid=$post_id;
$sql1=$con->prepare("SELECT * FROM comments where post_id=:pid");
$sql1->bindParam(':pid',$pid);
$sql1->execute();
$results1=$sql1->fetchAll(PDO::FETCH_ASSOC);
foreach($results1 as $comment){
echo "<br><b><cite>".$comment['comment_author']."</cite></b><br>";
echo $comment['comment_body']."<br>";
}
?>
save_comments.php
<?php
include 'config.php';
$comment_body=$_POST['cbody'];
$comment_author=$_POST['cauth'];
$post_id=$_POST['pid'];
$sql2=$con->prepare("INSERT INTO comments Values(NULL,:pid,:cauth,:cbody)");
$sql2->bindParam(':pid',$post_id);
$sql2->bindParam(':cauth',$comment_author);
$sql2->bindParam(':cbody',$comment_body);
$sql2->execute();
?>
PS:我还是 AJAX 和 jquery 的初学者
您没有将 ajax 请求定义为 a POST
,因此没有发送 POST 变量。
$.ajax({
data:$('#comment_form_'+post_id).serialize(),
url:'save_comments.php',
async : true,
method: 'POST', <---- ADD THIS
success: function(){
$("#comments_"+post_id).load("comments.php", {
post_id:post_id
});
}
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句