我在我的博客上添加了评论系统,问题是我无法在数据库上插入评论,我猜是因为它无法获取当前博客的帖子ID。从comments.php,数据将传递给post_comments.php。我怎样才能在ajax部分(脚本标签下)传递post_id?这是我第一次使用ajax,所以我对它并不是很好。任何帮助将不胜感激
comments.php:
<form method='post' action="" onsubmit="return post();">
<textarea id="comment" placeholder="Write Your Comment Here....."></textarea>
<br>
<input type="text" id="username" placeholder="Your Name">
<br>
<input type="submit" value="Post Comment">
</form>
<div id="all_comments">
<?php
$host="localhost";
$username="root";
$password="";
$databasename="comments";
$connect=mysql_connect($host,$username,$password);
$db=mysql_select_db($databasename);
$comm = mysql_query("select name,comment,post_time from comments order by post_time desc");
while($row=mysql_fetch_array($comm))
{
$name=$row['name'];
$comment=$row['comment'];
$time=$row['post_time'];
?>
<div class="comment_div">
<p class="name">Posted By:<?php echo $name;?></p>
<p class="comment"><?php echo $comment;?></p>
<p class="time"><?php echo $time;?></p>
</div>
<?php
}
?>
</div>
post_comments.php
<?php
$host="localhost";
$username="root";
$password="";
$databasename="comments";
$connect=mysql_connect($host,$username,$password);
$db=mysql_select_db($databasename);
if(isset($_POST['user_comm']) && isset($_POST['user_name']))
{
$comment=$_POST['user_comm'];
$name=$_POST['user_name'];
$insert=mysql_query("insert into comments values('','$name','$comment',CURRENT_TIMESTAMP)");
$select=mysql_query("select name,comment,post_time from comments where name='$name' and comment='$comment' ");
if($row=mysql_fetch_array($select))
{
$name=$row['name'];
$comment=$row['comment'];
$time=$row['post_time'];
?>
<div class="comment_div">
<p class="name">Posted By:<?php echo $name;?></p>
<p class="comment"><?php echo $comment;?></p>
<p class="time"><?php echo $time;?></p>
</div>
<?php
}
exit;
}
?>
答案 0 :(得分:1)
您需要传递post_id
。因此,您需要将post_id
存储到隐藏字段中。并在Ajax
电话代码中进行检查。
<强>的comments.php 强>
......
<input type="hidden" id="post_id" name="post_id" value="<?php echo $post_id?>">
<input type="submit" value="Post Comment">
......
<强> post_comments.php 强>
......
if(isset($_POST['user_comm']) && isset($_POST['user_name']) && isset($_POST['post_id']))
{
$post_id=$_POST['post_id'];
// do what ever you wanted to do with post_id
$comment=$_POST['user_comm'];
......