我有一个原始的评论系统,可以在其中发布评论。当点击post按钮时,一个AJAX请求被发送到php文件(process.php)。在process.php中,有一个while循环,它检索所有评论并将其作为数据发送回index.php文件。
问题是当我发布两条评论时,我在当前评论之前发布的评论会显示在指定的div中
index.php
if(isset($_POST['text'])){
if(!empty($_POST['text'])){
$text = $_POST['text'];
$query = mysql_query("INSERT INTO `test` VALUES('', '$text')");
}
}
?>
<form action="" class="comment_post" method="POST">
<input type="text" name="text">
<input type="submit" value="POST">
</form>
<hr>
<div id="comments">
</div>
<script>
$('form.comment_post').on('submit', function(){
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value= that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data
});
return false;
});
$('input[type=submit]').click(function(){
$.ajax({
type : 'POST',
url : 'process.php',
data : {action: 'retrieve'},
success : function(data){
$('#comments').html(data);
}
});
});
</script>
process.php
if(isset($_POST['action']) && !empty($_POST['action'])){
$action = $_POST['action'];
if($action == 'retrieve'){
$data = mysql_query("SELECT * FROM `test`");
if(mysql_num_rows($data) != 0){
while($row = mysql_fetch_assoc($data)){
$text = $row['text'];
echo '<div class="each_comment">'.$text.'</div><br>';
}
} else {
echo 'No data to retrieve';
}
}
}
?>
首先通过列"dateCreated"扩展数据库
然后使用这个插入代码:
$query = mysql_query("INSERT INTO `test`,`dateCreated` VALUES('', '$text','NOW()')");
在您的进程中.php使用如下代码:
$data = mysql_query("SELECT * FROM `test` ORDER BY `dateCreated` DESC ");