我正在使用ajax将评论发布到某个页面,我有一切正常工作,除非用户发布评论我希望它立即显示而不刷新。我必须显示评论的PHP代码是:
<?php
require('connect.php');
$query = "select * \n"
. " from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '$s_post_id' ORDER BY comments.id DESC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$c_comment_by = $row['comment_by'];
$c_comment_content = $row['comment_content'];
?>
<div class="comment_box">
<p><?php echo $c_comment_by;?></p>
<p><?php echo $c_comment_content;?></p>
</div>
<?php } ?>
</div>
</div>
<?php
}
}
我要发表评论的代码是:
<?php
$post_comment = $_POST['p_post_comment'];
$post_id = $_POST['p_post_id'];
$post_comment_by = "Undefined";
if ($post_comment){
if(require('connect.php')){
mysql_query("INSERT INTO comments VALUES (
'',
'$post_id',
'$post_comment_by',
'$post_comment'
)");
echo " <script>$('#post_form')[0].reset();</script>";
echo "success!";
mysql_close();
}else echo "Could no connect to the database!";
}
else echo "You cannot post empty comments!"
?>
JS:
function post(){
var post_comment = $('#comment').val();
$.post('comment_parser.php', {p_post_comment:post_comment,p_post_id:<?php echo $post_id;?>},
function(data)
{
$('#result').html(data);
});
}
这是我到目前为止所做的更新:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('.comment_box').load('blogpost.php');
}, 3000);.
});
现在我想做的是每次添加新的时都使用ajax刷新注释。没有刷新整个页面,当然。我做错了什么?
答案 0 :(得分:0)
您需要重组为端点结构。你将有一个名为“get_comments.php”的文件,它返回JSON中的最新注释,然后像这样调用一些JS:
function load_comments(){
$.ajax({
url: "API/get_comments.php",
data: {post_id: post_id, page: 0, limit: 0}, // If you want to do pagination eventually.
dataType: 'json',
success: function(response){
$('#all_comments').html(''); // Clears all HTML
// Insert each comment
response.forEach(function(comment){
var new_comment = "<div class="comment_box"><p>"+comment.comment_by+"</p><p>"+comment.comment_content+"</p></div>";
$('#all_comments').append(new_comment);
}
})
};
}
确保post_id
在某处全局声明,即。
<head>
<script>
var post_id = "<?= $s_post_id ; ?>";
</script>
</head>
您的新PHP文件如下所示:
require('connect.php');
$query = "select * from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '".$_REQUEST['post_id']."' ORDER BY comments.id DESC";
$result = mysql_query($query);
$all_comments = array() ;
while ($row = mysql_fetch_array($result))
$all_comments[] = array("comment_by" => $result[comment_by], "comment_content" => $result[comment_content]);
echo json_encode($all_comments);
当然,你想要遵循各地的良好做法,可能使用服务器和模板的模板。客户端HTML创建,永远不会像你写的那样编写MySQL查询(或者我为你写的)。使用MySQLi或PDO!想想如果$ s_post_id在某种程度上等于5' OR '1'='1
将会发生什么会发生这种情况只会返回每条评论..但是如果这是在DELETE_COMMENT函数中完成的,并且有人完全擦除了你的评论表呢?