我有一个原始评论系统,可以发表评论。单击post按钮时,会向php文件(process.php)发送一个AJAX请求。在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';
}
}
}
?>
答案 0 :(得分:0)
首先按“dateCreated”列扩展数据库
然后使用此插入代码:
$query = mysql_query("INSERT INTO `test`,`dateCreated` VALUES('', '$text','NOW()')");
你的process.php中的使用这样的代码:
$data = mysql_query("SELECT * FROM `test` ORDER BY `dateCreated` DESC ");