【发布时间】:2016-06-22 05:16:42
【问题描述】:
这是我的代码,我将comment 和post id(隐藏输入标签)传递给另一个php 文件comments.php,该文件应该将其插入db 并显示结果,但它没有发生。
这是我的表单 - echo 中引用的代码的一部分...我有一个自动递增 pid 与每个帖子相关联,因此对于每条评论,comment 和 pid 都存储在数据库中:
<form method=\"POST\" onSubmit=\"comment(); return false;\">
<input id=\"comment\" type=\"text\" placeholder=\"Add Comment...\" name=\"comment\">
<input type=\"hidden\" name=\"pid\" value=\"".$row['pid']."\">
<div class=\"z\"><input type=\"submit\" name=\"submit\" ></div>
</form>
JavaScript - 使用 onsubmit 为每个帖子的评论表单调用函数 comment()。
function comment() {
jQuery.ajax({
url: "comments.php",
data: $('form').serialize(),
type: "POST",
success:function(data){
$("#".$row['pid']).html(data);
},
error:function (){
}
});
}
这是comments.php 代码:
<?php
session_start();
include 'db.php';
$j =$_POST['comment'];
$k = $_POST['pid'];
$l =$_SESSION['uname'];
$sql = "INSERT INTO comments (pid,name,comment) values ('$k','$l','$j')";
$r = $conn->prepare($sql);
$r->execute();
if($r) {
echo '<div class="comment">
<a class="avatar">
<img style="height:30px;"src="zmf.jpg">
</a>
<div class="content">
<a class="author">'.$l.'</a>
<div class="metadata">
<span class="date">Today at 5:42PM</span>
</div>
<div class="text">';
echo $j.'</div>
<div class="actions">
</div>
</div>
</div>
';
}
?>
comments.php 应该返回的内容将显示在index.php 中的div 中,id = #postid 已在 index.php 中为每个帖子分配:
<div id=\"".$row['pid']."\">
</div>
index.php 对于每个帖子都有这样的div,因此评论完成的帖子,评论将显示在每个帖子下方的div。任何帮助将不胜感激。
我运行两个 while 循环来显示每个帖子的所有 previuos cmets 像这样。 第一个循环显示帖子和一个嵌套的while循环,每个帖子显示每个帖子的评论..以及while循环中每个帖子的评论表单以及一个id = postid的div来显示ajax结果..
$q = $conn->prepare("SELECT * FROM posts ORDER BY pid DESC");
$q->execute();
while($row = $q->fetch(PDO::FETCH_ASSOC)) {
#my post in div
#comment form
<form method=\"POST\" onsubmit=\"comment()\">
<input id=\"comment\" type=\"text\" placeholder=\"Add Comment...\" name=\"comment\">
<input type=\"hidden\" name=\"pid\" value=\"".$row['pid']."\">
<div class=\"z\"><input type=\"submit\" name=\"submit\" ></div>
</form>
#div where recent comment is shown using ajax
<div id=\"".$row['pid']."\">
</div>
#nested while loop for comments
$zmf = "SELECT * FROM comments WHERE pid = '" . $row['pid'] . "' ORDER BY comid DESC";
$zed = $conn->prepare($zmf);
$zed->execute();
$run = $zed->fetch();
while($run = $zed->fetch())
{
my div code and all..for comments
}
}
每个帖子都有一个 id pid .. 但它的工作不正常..请帮助
【问题讨论】:
-
你能展示完整的脚本吗?在你的javascript中激活
comment()? -
这是我文件中唯一的 js 部分......还有什么?
-
哦,对不起,我看到你做了什么,你有它内联。好吧无视!